本文主要用于工作記錄,在項目中遇到了就記錄一下
在早期,原生的JDK8是不支持HTTP/2協(xié)議的,所以,要想使用這個特性,需要有web服務(wù)器和應(yīng)用環(huán)境的支持,
例如:在VM中增加-Xbootclasspath/p:/Users/a1234/Downloads/alpn-boot-8.1.11.v20170118.jar
來配合使用
但是從8u252開始,ALPN層已經(jīng)從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 最大連接數(shù)
* @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請求示例文章來源:http://www.zghlxwxcb.cn/news/detail-621754.html
/**
* 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請求示例文章來源地址http://www.zghlxwxcb.cn/news/detail-621754.html
/**
* 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();
到了這里,關(guān)于jdk8使用okhttp發(fā)送http2請求的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!