欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

SpringBoot okhtt工具類封裝方式

 更新時(shí)間:2025年03月08日 10:46:21   作者:早起的年輕人  
本文介紹了如何在SpringBoot項(xiàng)目中使用OkHttp工具類進(jìn)行HTTP請(qǐng)求,并提供了一個(gè)封裝了GET和POST方法的工具類示例,在Controller中使用該工具類時(shí),需要注意OkHttpClient的靜態(tài)初始化和異常處理

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)文章

最新評(píng)論