jdk8使用okhttp发送http2请求

本文主要用于工作记录,在项目中遇到了就记录一下

在早期,原生的JDK8是不支持HTTP/2协议的,所以,要想使用这个特性,需要有web服务器和应用环境的支持,
例如:在VM中增加-Xbootclasspath/p:/Users/a1234/Downloads/alpn-boot-8.1.11.v20170118.jar来配合使用

但是从8u252开始,ALPN层已经从Java 11向后移植到了Java 8。意味着,只要使用Java
8u252或更新版本,不再要求使用Conscrypt和Jetty就可以使用HTTP/2了。

重点来了:一定要先检查自己的jdk版本是否大于8u252,然后就可以在项目中集成okhttp

项目pom配置

<!-- SpringBoot 依赖配置 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-dependencies</artifactId>
    <version>2.7.2</version>
    <type>pom</type>
    <scope>import</scope>
</dependency>

<!-- okhttp 依赖配置 -->
<dependency>
    <groupId>com.squareup.okhttp3</groupId>
    <artifactId>okhttp</artifactId>
    <version>4.9.3</version>
</dependency>

简单封装获取http2client请求

 	/**
     * 获取httpClient请求
     *
     * @param maxTotalConnections             最大连接数
     * @param connectionKeepAliveTimeInMillis 最长连接保持活动时间
     * @return
     */
    private static OkHttpClient createHttpClient(int maxTotalConnections, long connectionKeepAliveTimeInMillis) {
        ConnectionPool connectionPool = new ConnectionPool(maxTotalConnections, connectionKeepAliveTimeInMillis, TimeUnit.MILLISECONDS);
        return new OkHttpClient.Builder()
                .followRedirects(false)
//                .protocols(Collections.singletonList(Protocol.H2_PRIOR_KNOWLEDGE))
                .retryOnConnectionFailure(true)
                .connectionPool(connectionPool)
                .build();
    }

GET请求示例

	/**
     * GET请求示例
     *
     * @return
     * @throws IOException
     */
    private String getTokenResStr() throws IOException {Request request = new Request.Builder()
                .addHeader("Nonce",123)
                .addHeader("Authorization", configData.getAuthorizationCode())
                .url(“url地址”)
                .build();//GET by default
        OkHttpClient httpClient = createHttpClient(100, 30000);
        Response response = httpClient.newCall(request).execute();
        if (!response.isSuccessful()) {
            throw new IOException("Unexpected code " + response);
        }
        return response.body().string();
    }

POST请求示例

	/**
     * POST请求示例
     *
     * @param orderId
     * @param tokenResStr
     * @return
     * @throws IOException
     */
    private String getOrderDetail(String orderId, String tokenResStr) throws IOException {
        JSONObject tokenRes = JSONObject.parseObject(tokenResStr);
        // token
        String accessToken = tokenRes.getString("access_token");
        // token类型
        String tokenType = tokenRes.getString("token_type");

        String authorizationStr = firstUpperCase(tokenType) + " " + accessToken;
        Request request = new Request.Builder()
                .addHeader("Authorization", authorizationStr)
                .addHeader("Content-Type", "application/json")
                .url(configData.getDetailRpcUrl() + orderId)
                .build();
        OkHttpClient httpClient = createHttpClient(100, 30000);
        Response response = httpClient.newCall(request).execute();
        if (!response.isSuccessful()) {
            throw new IOException("Unexpected code " + response);
        }
        return response.body().string();

你可能感兴趣的:(项目问题积累,SpringBoot相关,okhttp,http2client,java)