亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

springboot中使用okhttp3的小結(jié)

 更新時(shí)間:2025年09月12日 09:29:14   作者:hero.fei  
OkHttp3是一個(gè)Java HTTP客戶端,可以處理各種請求類型,比如 GET、POST、PUT 等,并且支持高效的 HTTP 連接池、請求和響應(yīng)緩存、以及異步請求處理等,感興趣的可以了解一下

在 Spring Boot 項(xiàng)目中使用 OkHttp3 進(jìn)行 HTTP 請求是一個(gè)高效且流行的方式。OkHttp3 是一個(gè) Java HTTP 客戶端,可以處理各種請求類型,比如 GET、POST、PUT 等,并且支持高效的 HTTP 連接池、請求和響應(yīng)緩存、以及異步請求處理等。

maven項(xiàng)目中首先是需要引入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)建一個(gè)配置類,用于配置 OkHttpClient 實(shí)例。這是為了方便地進(jìn)行請求處理和注入到 Spring 中。如果項(xiàng)目中用的地方比較多就封裝成一個(gè)bean在使用的時(shí)候通過spring的注入方式即可使用,如果是臨時(shí)用一下可以直接在class中創(chuàng)建,通過static代碼塊初始化。

注冊bean的方式:

@Configuration
public class OkHttpConfig {

    // 創(chuàng)建 OkHttpClient Bean
    @Bean
    public OkHttpClient okHttpClient() {
//可以引入線程池單獨(dú)線程調(diào)用
         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 {

    // 余額最大空閑時(shí)間
    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 {
        // 構(gòu)建請求
        Request request = new Request.Builder()
                .url(url)
                .build();

        // 執(zhí)行請求并獲取響應(yīng)
        try (Response response = okHttpClient.newCall(request).execute()) {
            if (response.isSuccessful()) {
                // 返回響應(yīng)體內(nèi)容
                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"));

        // 構(gòu)建請求
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();

        // 執(zhí)行請求并獲取響應(yīng)
        try (Response response = okHttpClient.newCall(request).execute()) {
            if (response.isSuccessful()) {
                // 返回響應(yīng)體內(nèi)容
                return response.body().string();
            } else {
                return "Request failed with code: " + response.code();
            }
        }
    }
}

另外還可以發(fā)送異步請求,不需要使用使用 execute調(diào)用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());
                }
            }
        });
    }
}

到此這篇關(guān)于springboot中使用okhttp3的小結(jié)的文章就介紹到這了,更多相關(guān)springboot使用okhttp3內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論