简体   繁体   中英

Java OkHttp3 only use Http/1.1 OR Http/2

Trying to do some test-cases for HTTP requests. I want to distinguish between HTTP/1.1 and HTTP/2. In order to do that, I need to know which version I have used from a request. I also want to force the request to use HTTP/1.1 or HTTP/2. I am using OkHttp3 for Java. Here is a simple request which I do:

Request request = new Request.Builder()
            .url(url)
            .build();

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

You can force the request to be HTTP/1.1 only with the following code

new OkHttpClient.Builder().protocols(Arrays.asList(Protocol.HTTP_1_1));

You can't force HTTP/2 only as HTTP/1.1 must be in the protocols list.

However you can confirm by checking protocol on the Response object

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM