springboot中使用okhttp3的小結
在 Spring Boot 項目中使用 OkHttp3 進行 HTTP 請求是一個高效且流行的方式。OkHttp3 是一個 Java HTTP 客戶端,可以處理各種請求類型,比如 GET、POST、PUT 等,并且支持高效的 HTTP 連接池、請求和響應緩存、以及異步請求處理等。
maven項目中首先是需要引入pom文件:
<dependencies>
<!-- OkHttp3 dependency -->
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.9.0</version> <!-- 使用最新的穩(wěn)定版本 -->
</dependency>
</dependencies>
創(chuàng)建OkHttpClient配置類
接下來,你可以在 Spring Boot 中創(chuàng)建一個配置類,用于配置 OkHttpClient 實例。這是為了方便地進行請求處理和注入到 Spring 中。如果項目中用的地方比較多就封裝成一個bean在使用的時候通過spring的注入方式即可使用,如果是臨時用一下可以直接在class中創(chuàng)建,通過static代碼塊初始化。
注冊bean的方式:
@Configuration
public class OkHttpConfig {
// 創(chuàng)建 OkHttpClient Bean
@Bean
public OkHttpClient okHttpClient() {
//可以引入線程池單獨線程調用
CONNECTION_POOL = new ConnectionPool(1024, 5, TimeUnit.MINUTES);
OK_HTTP_CLIENT = new OkHttpClient.Builder()
.connectionPool(CONNECTION_POOL)
.connectTimeout(10, TimeUnit.SECONDS)
.readTimeout(1, TimeUnit.MINUTES)
.retryOnConnectionFailure(true)
.pingInterval(Duration.ofSeconds(59))
.build();
}
}在class類中直接使用:
@Slf4j
@Service
public class http3Test {
// 余額最大空閑時間
private final static int idleTime = 60 * 60 * 24;
private static final OkHttpClient OK_HTTP_CLIENT;
private static final ConnectionPool CONNECTION_POOL;
static {
CONNECTION_POOL = new ConnectionPool(1024, 5, TimeUnit.MINUTES);
OK_HTTP_CLIENT = new OkHttpClient.Builder()
.connectionPool(CONNECTION_POOL)
.connectTimeout(10, TimeUnit.SECONDS)
.readTimeout(1, TimeUnit.MINUTES)
.retryOnConnectionFailure(true)
.pingInterval(Duration.ofSeconds(59))
.build();
}發(fā)送get請求:
@Service
public class OkHttpService {
@Autowired
private OkHttpClient okHttpClient;
public String sendGetRequest(String url) throws IOException {
// 構建請求
Request request = new Request.Builder()
.url(url)
.build();
// 執(zhí)行請求并獲取響應
try (Response response = okHttpClient.newCall(request).execute()) {
if (response.isSuccessful()) {
// 返回響應體內容
return response.body().string();
} else {
return "Request failed with code: " + response.code();
}
}
}
}發(fā)送post請求:
@Service
public class OkHttpService {
@Autowired
private OkHttpClient okHttpClient;
public String sendPostRequest(String url, String jsonBody) throws IOException {
// 創(chuàng)建請求體
RequestBody body = RequestBody.create(jsonBody, MediaType.get("application/json; charset=utf-8"));
// 構建請求
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
// 執(zhí)行請求并獲取響應
try (Response response = okHttpClient.newCall(request).execute()) {
if (response.isSuccessful()) {
// 返回響應體內容
return response.body().string();
} else {
return "Request failed with code: " + response.code();
}
}
}
}另外還可以發(fā)送異步請求,不需要使用使用 execute調用http3提供的enqueue方法:
import okhttp3.*;
public class AsyncOkHttpService {
private OkHttpClient okHttpClient = new OkHttpClient();
public void sendAsyncGetRequest(String url) {
Request request = new Request.Builder().url(url).build();
okHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
System.out.println("Request failed: " + e.getMessage());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (response.isSuccessful()) {
System.out.println("Response: " + response.body().string());
} else {
System.out.println("Request failed with code: " + response.code());
}
}
});
}
}
到此這篇關于springboot中使用okhttp3的小結的文章就介紹到這了,更多相關springboot使用okhttp3內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
java開發(fā)MVC三層架構上再加一層Manager層原理詳解
這篇文章主要為大家介紹了MVC三層架構中再加一層Manager層原理的示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步2021-10-10
基于Java中對域和靜態(tài)方法的訪問不具有多態(tài)性(實例講解)
下面小編就為大家?guī)硪黄贘ava中對域和靜態(tài)方法的訪問不具有多態(tài)性(實例講解)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-10-10
高效數(shù)據(jù)傳輸?shù)拿孛芪淦鱌rotobuf的使用教程
Protobuf(Protocol?Buffers)是由?Google?開發(fā)的一種輕量級、高效的數(shù)據(jù)交換格式,它被用于結構化數(shù)據(jù)的序列化、反序列化和傳輸,本文主要介紹了它的具體使用方法,需要的可以參考一下2023-05-05
SpringMVC中的DispatcherServlet結構和初始化詳解
這篇文章主要介紹了SpringMVC中的DispatcherServlet結構和初始化詳解,SpringMVC中Spring容器的關系是通過監(jiān)聽方式啟動的,那么Spring與Servlet的Web容器(如:Tomcat、jetty)的關系則是通過DispatcherServlet進行關聯(lián),需要的朋友可以參考下2024-01-01
詳解如何開發(fā)一個MyBatis通用Mapper的輪子
因為一些原因,例如:通用數(shù)據(jù)權限控制、MyBatis-Plus好像不支持聯(lián)合主鍵等,我們不得不開發(fā)一個MyBatis通用Mapper的輪子。文中的示例代碼講解詳細,需要的可以參考一下2022-12-12

