如何在Android设备上使用http / 2和Okhttp?

时间:2015-08-06 08:11:01

标签: android http okhttp http2

我正在测试支持HTTP / 2的网站like this, 我尝试使用okhttp发送请求:

OkHttpClient okHttpClient = new OkHttpClient();

Request request = new Request.Builder()
        .url("https://www.google.it")
        .build();


okHttpClient.newCall(request).enqueue(new Callback() {
    @Override
    public void onFailure(Request request, IOException e) {
        e.printStackTrace();
    }

    @Override
    public void onResponse(Response response) throws IOException {
        Log.d("TestHttp", "OkHttp-Selected-Protocol: " + response.header("OkHttp-Selected-Protocol"));
        Log.d("TestHttp", "Response code is " + response.code());
    }
});

在日志中我得到了这样的东西:

OkHttp-Selected-Protocol: http/1.1

okhttpClient选择使用http / 1.1,如何强制它使用HTTP / 2?

1 个答案:

答案 0 :(得分:3)

Okhttp 2.5+仅通过ALPN支持5.0以上的http / 2.

但您可以通过NPN修改源代码以支持高于4.0+的http / 2。