SpringBoot okhtt工具類封裝方式
SpringBoot okhtt工具類封裝
在 Spring Boot 項(xiàng)目中使用 OkHttp 可以方便地進(jìn)行 HTTP 請(qǐng)求。
在pom.xml文件中添加 OkHttp 的依賴:
<dependencies> <!-- OkHttp --> <dependency> <groupId>com.squareup.okhttp3</groupId> <artifactId>okhttp</artifactId> <version>4.9.3</version> </dependency> </dependencies>
以下是一個(gè)封裝了常見(jiàn) HTTP 請(qǐng)求方法(GET、POST)的 OkHttp 工具類示例
import okhttp3.*; import java.io.IOException; import java.util.Map; import java.util.concurrent.TimeUnit; /** * OkHttp 工具類,封裝常見(jiàn)的 HTTP 請(qǐng)求方法 */ public class OkHttpUtils { private static final OkHttpClient client; static { // 初始化 OkHttpClient client = new OkHttpClient.Builder() .connectTimeout(10, TimeUnit.SECONDS) // 連接超時(shí)時(shí)間 .readTimeout(30, TimeUnit.SECONDS) // 讀取超時(shí)時(shí)間 .writeTimeout(30, TimeUnit.SECONDS) // 寫(xiě)入超時(shí)時(shí)間 .build(); } /** * 發(fā)送 GET 請(qǐng)求 * * @param url 請(qǐng)求的 URL * @return 響應(yīng)結(jié)果字符串 * @throws IOException 網(wǎng)絡(luò)請(qǐng)求異常 */ public static String sendGetRequest(String url) throws IOException { Request request = new Request.Builder() .url(url) .build(); try (Response response = client.newCall(request).execute()) { if (response.isSuccessful() && response.body() != null) { return response.body().string(); } return null; } } /** * 發(fā)送帶參數(shù)的 GET 請(qǐng)求 * * @param url 請(qǐng)求的 URL * @param params 請(qǐng)求參數(shù) * @return 響應(yīng)結(jié)果字符串 * @throws IOException 網(wǎng)絡(luò)請(qǐng)求異常 */ public static String sendGetRequest(String url, Map<String, String> params) throws IOException { HttpUrl.Builder urlBuilder = HttpUrl.parse(url).newBuilder(); if (params != null) { for (Map.Entry<String, String> entry : params.entrySet()) { urlBuilder.addQueryParameter(entry.getKey(), entry.getValue()); } } String finalUrl = urlBuilder.build().toString(); return sendGetRequest(finalUrl); } /** * 發(fā)送 POST 請(qǐng)求,請(qǐng)求體為 JSON 格式 * * @param url 請(qǐng)求的 URL * @param jsonBody JSON 格式的請(qǐng)求體 * @return 響應(yīng)結(jié)果字符串 * @throws IOException 網(wǎng)絡(luò)請(qǐng)求異常 */ public static String sendPostRequest(String url, String jsonBody) throws IOException { MediaType JSON = MediaType.get("application/json; charset=utf-8"); RequestBody body = RequestBody.create(jsonBody, JSON); Request request = new Request.Builder() .url(url) .post(body) .build(); try (Response response = client.newCall(request).execute()) { if (response.isSuccessful() && response.body() != null) { return response.body().string(); } return null; } } /** * 發(fā)送 POST 請(qǐng)求,請(qǐng)求體為表單格式 * * @param url 請(qǐng)求的 URL * @param params 表單參數(shù) * @return 響應(yīng)結(jié)果字符串 * @throws IOException 網(wǎng)絡(luò)請(qǐng)求異常 */ public static String sendPostFormRequest(String url, Map<String, String> params) throws IOException { FormBody.Builder formBodyBuilder = new FormBody.Builder(); if (params != null) { for (Map.Entry<String, String> entry : params.entrySet()) { formBodyBuilder.add(entry.getKey(), entry.getValue()); } } RequestBody formBody = formBodyBuilder.build(); Request request = new Request.Builder() .url(url) .post(formBody) .build(); try (Response response = client.newCall(request).execute()) { if (response.isSuccessful() && response.body() != null) { return response.body().string(); } return null; } } }
使用示例
以下是如何在 Spring Boot 的 Controller 中使用這個(gè)工具類:
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.io.IOException; import java.util.HashMap; import java.util.Map; @RestController @RequestMapping("/http") public class HttpController { @GetMapping("/get") public String getRequest() throws IOException { String url = "https://jsonplaceholder.typicode.com/todos/1"; return OkHttpUtils.sendGetRequest(url); } @GetMapping("/getWithParams") public String getRequestWithParams() throws IOException { String url = "https://jsonplaceholder.typicode.com/posts"; Map<String, String> params = new HashMap<>(); params.put("userId", "1"); return OkHttpUtils.sendGetRequest(url, params); } @GetMapping("/postJson") public String postJsonRequest() throws IOException { String url = "https://jsonplaceholder.typicode.com/posts"; String jsonBody = "{\"title\":\"foo\",\"body\":\"bar\",\"userId\":1}"; return OkHttpUtils.sendPostRequest(url, jsonBody); } @GetMapping("/postForm") public String postFormRequest() throws IOException { String url = "https://jsonplaceholder.typicode.com/posts"; Map<String, String> params = new HashMap<>(); params.put("title", "foo"); params.put("body", "bar"); params.put("userId", "1"); return OkHttpUtils.sendPostFormRequest(url, params); } }
注意事項(xiàng)
- 此工具類中的
OkHttpClient
是靜態(tài)初始化的,在整個(gè)應(yīng)用程序中共享一個(gè)實(shí)例,以提高性能和復(fù)用連接。 - 對(duì)于異常處理,當(dāng)前示例只是簡(jiǎn)單地將
IOException
拋出,在實(shí)際應(yīng)用中,你可能需要根據(jù)具體情況進(jìn)行更詳細(xì)的異常處理,例如記錄日志、返回合適的錯(cuò)誤信息等。 - 確保在使用時(shí)處理好可能的網(wǎng)絡(luò)異常和超時(shí)情況,以保證應(yīng)用程序的健壯性。
總結(jié)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
Java實(shí)現(xiàn)簡(jiǎn)單的分頁(yè)功能
這篇文章主要為大家詳細(xì)介紹了Java實(shí)現(xiàn)簡(jiǎn)單的分頁(yè)功能,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-08-08基于Mybatis plus 自動(dòng)代碼生成器的實(shí)現(xiàn)代碼
本文通過(guò)實(shí)例代碼給大家介紹了基于Mybatis-plus 自動(dòng)代碼生成器的相關(guān)知識(shí),非常不錯(cuò),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2018-05-05Kotlin傳遞可變長(zhǎng)參數(shù)給Java可變參數(shù)實(shí)例代碼
這篇文章主要介紹了Kotlin傳遞可變長(zhǎng)參數(shù)給Java可變參數(shù)實(shí)例代碼,小編覺(jué)得還是挺不錯(cuò)的,具有一定借鑒價(jià)值,需要的朋友可以參考下2018-01-01Java+Swing實(shí)現(xiàn)醫(yī)院管理系統(tǒng)的完整代碼
這篇文章主要介紹了Java+Swing實(shí)現(xiàn)醫(yī)院管理系統(tǒng)的完整代碼,代碼簡(jiǎn)單易懂,對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-05-05postgresql 實(shí)現(xiàn)16進(jìn)制字符串轉(zhuǎn)10進(jìn)制數(shù)字
這篇文章主要介紹了postgresql 實(shí)現(xiàn)16進(jìn)制字符串轉(zhuǎn)10進(jìn)制數(shù)字操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2021-02-02mybatis3中@SelectProvider傳遞參數(shù)方式
這篇文章主要介紹了mybatis3中@SelectProvider傳遞參數(shù)方式。具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-08-08