Java OkHttp3只使用Http / 1.1或Http / 2

尝试为HTTP请求执行一些测试用例.我想区分HTTP / 1.1和HTTP / 2.为了做到这一点,我需要知道我从请求中使用了哪个版本.我还想强制请求使用HTTP / 1.1或HTTP / 2.我正在使用OkHttp3 for Java.
这是一个简单的请求,我这样做:
Request request = new Request.Builder()
            .url(url)
            .build();

Response response = client.newCall(request).execute();
return response.body().string();

解决方法

您可以使用以下代码强制请求为HTTP / 1.1
new OkHttpClient.Builder().protocols(Arrays.asList(Protocol.HTTP_1_1));

您不能强制HTTP / 2,因为HTTP / 1.1必须在protocols列表中.

但是,您可以通过检查Response对象上的protocol来确认

Request request = new Request.Builder()
        .url("http://publicobject.com/helloworld.txt")
        .build();

Response response = client.newCall(request).execute();

assert(response.protocol() == Protocol.HTTP_2);

相关文章

最近看了一下学习资料,感觉进制转换其实还是挺有意思的,尤...
/*HashSet 基本操作 * --set:元素是无序的,存入和取出顺序不...
/*list 基本操作 * * List a=new List(); * 增 * a.add(inde...
/* * 内部类 * */ 1 class OutClass{ 2 //定义外部类的成员变...
集合的操作Iterator、Collection、Set和HashSet关系Iterator...
接口中常量的修饰关键字:public,static,final(常量)函数...