hutool 的HttpUtil是http1还是http2方式

Hutool 的 HttpUtil 工具类是基于 Apache HttpClient 4.x 实现的,因此默认使用的是 HTTP 1.1 协议。但是,HttpClient 4.3 及以上版本已经支持 HTTP 2 协议,可以通过特定的配置启用 HTTP 2 支持。

要启用 HttpClient 的 HTTP 2 支持,需要使用自定义的 HttpClientBuilder 对象进行配置。以下是一个示例代码:

public class HttpUtilExample {
    public static void main(String[] args) throws IOException {
        CloseableHttpClient httpClient = HttpClientBuilder.create()
                .setSSLHostnameVerifier(new NoopHostnameVerifier())
                .setConnectionReuseStrategy(NoConnectionReuseStrategy.INSTANCE)
                .setConnectionManager(new PoolingHttpClientConnectionManager(
                        RegistryBuilder.<ConnectionSocketFactory>create()
                                .register("http", PlainConnectionSocketFactory.getSocketFactory())
                                .register("https", SSLConnectionSocketFactory.getSystemSocketFactory())
                                .build(),
                        null,
                        null,
                        null,
                        -1,
                        TimeUnit.MILLISECONDS,
                        new SystemDefaultDnsResolver()))
                .setRetryHandler(new DefaultHttpRequestRetryHandler(3, true))
                .setUserAgent(HttpClients.USER_AGENT)
                .setProtocolVersion(HttpVersion.HTTP_2)
                .build();

        String response = HttpUtil.createGet("https://http2.pro/api/v1")
                .setHttpClient(httpClient)
                .execute()
                .body();

        System.out.println(response);
    }
}

 

在上面的示例中,首先创建了一个自定义的 HttpClientBuilder 对象,并通过 setProtocolVersion() 方法将协议版本设置为 HTTP 2。然后使用该对象创建了一个 CloseableHttpClient 对象,并通过 setHttpClient() 方法将其设置为 HttpUtil 的默认 HttpClient。最后发送了一个 HTTP GET 请求,并输出了响应结果。

需要注意的是,在使用 HttpClient 发送 HTTP 2 请求时,还需要进行一些其他的配置,如设置 SSL HostnameVerifier、ConnectionReuseStrategy、ConnectionManager、RetryHandler 等。上面的示例代码已经包含了这些配置,可以直接使用。

posted @ 2023-03-11 08:34  锐洋智能  阅读(643)  评论(0编辑  收藏  举报