okhttp的相关使用

我爱海鲸 2026-01-20 11:13:08 暂无标签

简介4.12.0

5.x的版本引入之后好像无法使用,所以使用这个稳定版本的

1、引入maven依赖:

<!-- Source: https://mvnrepository.com/artifact/com.squareup.okhttp3/okhttp -->
<dependency>
    <groupId>com.squareup.okhttp3</groupId>
    <artifactId>okhttp</artifactId>
    <version>4.12.0</version>
    <scope>compile</scope>
</dependency>

<!-- Source: https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.20.0</version>
    <scope>compile</scope>
</dependency>

2、OkHttpConfig配置:

import lombok.extern.slf4j.Slf4j;
import okhttp3.ConnectionPool;
import okhttp3.OkHttpClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import jakarta.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * OkHttp配置类
 * 
 * @author system
 */
@Slf4j
@Configuration
public class OkHttpConfig {

    @Resource
    private OkHttpProperties okHttpProperties;

    /**
     * 创建OkHttpClient Bean
     * 
     * @return OkHttpClient实例
     */
    @Bean
    public OkHttpClient okHttpClient() {
        // 创建连接池
        ConnectionPool connectionPool = new ConnectionPool(
                okHttpProperties.getMaxIdleConnections(),
                okHttpProperties.getKeepAliveDuration(),
                TimeUnit.MINUTES
        );

        // 构建OkHttpClient
        OkHttpClient.Builder builder = new OkHttpClient.Builder()
                .connectTimeout(okHttpProperties.getConnectTimeout(), TimeUnit.SECONDS)
                .readTimeout(okHttpProperties.getReadTimeout(), TimeUnit.SECONDS)
                .writeTimeout(okHttpProperties.getWriteTimeout(), TimeUnit.SECONDS)
                .connectionPool(connectionPool)
                .retryOnConnectionFailure(okHttpProperties.getRetryOnConnectionFailure());

        // 如果启用日志拦截器,添加日志拦截器
        if (Boolean.TRUE.equals(okHttpProperties.getEnableLoggingInterceptor())) {
            builder.addInterceptor(chain -> {
                okhttp3.Request request = chain.request();
                long startTime = System.currentTimeMillis();
                log.info("OkHttp请求: {} {}", request.method(), request.url());
                
                okhttp3.Response response = chain.proceed(request);
                long endTime = System.currentTimeMillis();
                log.info("OkHttp响应: {} {} 耗时: {}ms", 
                        response.code(), 
                        response.message(), 
                        (endTime - startTime));
                
                return response;
            });
        }

        OkHttpClient client = builder.build();
        log.info("OkHttpClient配置完成 - 连接超时: {}s, 读取超时: {}s, 写入超时: {}s, 最大空闲连接: {}, 保持连接时间: {}分钟",
                okHttpProperties.getConnectTimeout(),
                okHttpProperties.getReadTimeout(),
                okHttpProperties.getWriteTimeout(),
                okHttpProperties.getMaxIdleConnections(),
                okHttpProperties.getKeepAliveDuration());

        return client;
    }
}

3、OkHttpProperties配置:

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import lombok.Data;

/**
 * OkHttp配置属性
 * 
 * @author system
 */
@Data
@Component
@ConfigurationProperties(prefix = "okhttp")
public class OkHttpProperties {
    
    /**
     * 连接超时时间(秒),默认30秒
     */
    private Integer connectTimeout = 30;
    
    /**
     * 读取超时时间(秒),默认30秒
     */
    private Integer readTimeout = 30;
    
    /**
     * 写入超时时间(秒),默认30秒
     */
    private Integer writeTimeout = 30;
    
    /**
     * 连接池最大空闲连接数,默认5
     */
    private Integer maxIdleConnections = 5;
    
    /**
     * 连接池中连接的最大存活时间(分钟),默认5分钟
     */
    private Long keepAliveDuration = 5L;
    
    /**
     * 是否启用重试,默认false
     */
    private Boolean retryOnConnectionFailure = false;
    
    /**
     * 是否启用日志拦截器,默认false
     */
    private Boolean enableLoggingInterceptor = false;
}

4、application配置:

# OkHttp配置
okhttp:
  # 连接超时时间(秒),默认30秒
  connect-timeout: 30
  # 读取超时时间(秒),默认30秒
  read-timeout: 30
  # 写入超时时间(秒),默认30秒
  write-timeout: 30
  # 连接池最大空闲连接数,默认5
  max-idle-connections: 5
  # 连接池中连接的最大存活时间(分钟),默认5分钟
  keep-alive-duration: 5
  # 是否启用重试,默认false
  retry-on-connection-failure: false
  # 是否启用日志拦截器,默认false
  enable-logging-interceptor: false

5、请求的工具类:

import java.io.IOException;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;

import lombok.extern.slf4j.Slf4j;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * OkHttp工具类
 * 
 * @author system
 */
@Slf4j
public class OkHttpUtil {

    private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");

    /**
     * GET请求
     * 
     * @param client OkHttpClient实例
     * @param url 请求URL
     * @return 响应内容
     */
    public static String get(OkHttpClient client, String url) {
        return get(client, url, null);
    }

    /**
     * GET请求(带请求头)
     * 
     * @param client OkHttpClient实例
     * @param url 请求URL
     * @param headers 请求头
     * @return 响应内容
     */
    public static String get(OkHttpClient client, String url, Map<String, String> headers) {
        Request.Builder requestBuilder = new Request.Builder().url(url);
        
        if (headers != null && !headers.isEmpty()) {
            headers.forEach(requestBuilder::addHeader);
        }
        
        Request request = requestBuilder.build();
        return execute(client, request);
    }

    /**
     * POST请求(JSON格式)
     * 
     * @param client OkHttpClient实例
     * @param url 请求URL
     * @param jsonBody JSON请求体
     * @return 响应内容
     */
    public static String postJson(OkHttpClient client, String url, String jsonBody) {
        return postJson(client, url, jsonBody, null);
    }

    /**
     * POST请求(JSON格式,带请求头)
     * 
     * @param client OkHttpClient实例
     * @param url 请求URL
     * @param jsonBody JSON请求体
     * @param headers 请求头
     * @return 响应内容
     */
    public static String postJson(OkHttpClient client, String url, String jsonBody, Map<String, String> headers) {
        RequestBody body = RequestBody.create(
                StringUtils.isBlank(jsonBody) ? "" : jsonBody, 
                JSON
        );
        
        Request.Builder requestBuilder = new Request.Builder()
                .url(url)
                .post(body);
        
        if (headers != null && !headers.isEmpty()) {
            headers.forEach(requestBuilder::addHeader);
        }
        
        Request request = requestBuilder.build();
        return execute(client, request);
    }

    /**
     * POST请求(表单格式)
     * 
     * @param client OkHttpClient实例
     * @param url 请求URL
     * @param formParams 表单参数
     * @return 响应内容
     */
    public static String postForm(OkHttpClient client, String url, Map<String, String> formParams) {
        return postForm(client, url, formParams, null);
    }

    /**
     * POST请求(表单格式,带请求头)
     * 
     * @param client OkHttpClient实例
     * @param url 请求URL
     * @param formParams 表单参数
     * @param headers 请求头
     * @return 响应内容
     */
    public static String postForm(OkHttpClient client, String url, Map<String, String> formParams, Map<String, String> headers) {
        FormBody.Builder formBuilder = new FormBody.Builder();
        
        if (formParams != null && !formParams.isEmpty()) {
            formParams.forEach(formBuilder::add);
        }
        
        RequestBody body = formBuilder.build();
        
        Request.Builder requestBuilder = new Request.Builder()
                .url(url)
                .post(body);
        
        if (headers != null && !headers.isEmpty()) {
            headers.forEach(requestBuilder::addHeader);
        }
        
        Request request = requestBuilder.build();
        return execute(client, request);
    }

    /**
     * PUT请求(JSON格式)
     * 
     * @param client OkHttpClient实例
     * @param url 请求URL
     * @param jsonBody JSON请求体
     * @return 响应内容
     */
    public static String putJson(OkHttpClient client, String url, String jsonBody) {
        return putJson(client, url, jsonBody, null);
    }

    /**
     * PUT请求(JSON格式,带请求头)
     * 
     * @param client OkHttpClient实例
     * @param url 请求URL
     * @param jsonBody JSON请求体
     * @param headers 请求头
     * @return 响应内容
     */
    public static String putJson(OkHttpClient client, String url, String jsonBody, Map<String, String> headers) {
        RequestBody body = RequestBody.create(
                StringUtils.isBlank(jsonBody) ? "" : jsonBody, 
                JSON
        );
        
        Request.Builder requestBuilder = new Request.Builder()
                .url(url)
                .put(body);
        
        if (headers != null && !headers.isEmpty()) {
            headers.forEach(requestBuilder::addHeader);
        }
        
        Request request = requestBuilder.build();
        return execute(client, request);
    }

    /**
     * DELETE请求
     * 
     * @param client OkHttpClient实例
     * @param url 请求URL
     * @return 响应内容
     */
    public static String delete(OkHttpClient client, String url) {
        return delete(client, url, null);
    }

    /**
     * DELETE请求(带请求头)
     * 
     * @param client OkHttpClient实例
     * @param url 请求URL
     * @param headers 请求头
     * @return 响应内容
     */
    public static String delete(OkHttpClient client, String url, Map<String, String> headers) {
        Request.Builder requestBuilder = new Request.Builder().url(url).delete();
        
        if (headers != null && !headers.isEmpty()) {
            headers.forEach(requestBuilder::addHeader);
        }
        
        Request request = requestBuilder.build();
        return execute(client, request);
    }

    /**
     * 执行请求
     * 
     * @param client OkHttpClient实例
     * @param request 请求对象
     * @return 响应内容
     */
    private static String execute(OkHttpClient client, Request request) {
        long startTime = System.currentTimeMillis();
        
        try (Response response = client.newCall(request).execute()) {
            long endTime = System.currentTimeMillis();
            long duration = endTime - startTime;
            
            ResponseBody responseBody = response.body();
            String bodyString = "";
            
            if (responseBody != null) {
                bodyString = responseBody.string();
            } else {
                log.warn("请求响应体为空,URL: {}, 耗时: {}ms", request.url(), duration);
            }
            
            if (response.isSuccessful()) {
                log.debug("请求成功,URL: {}, 状态码: {}, 耗时: {}ms", 
                        request.url(), response.code(), duration);
            } else {
                log.warn("请求失败,URL: {}, 状态码: {}, 响应: {}, 耗时: {}ms", 
                        request.url(), response.code(), bodyString, duration);
            }
            
            return bodyString;
            
        } catch (IOException e) {
            long endTime = System.currentTimeMillis();
            long duration = endTime - startTime;
            log.error("请求异常,URL: {}, 耗时: {}ms", request.url(), duration, e);
            throw new RuntimeException("HTTP请求异常: " + e.getMessage(), e);
        }
    }

    /**
     * 执行请求并返回Response对象(用于需要获取响应头等信息的场景)
     * 注意:调用者需要负责关闭Response对象
     * 
     * @param client OkHttpClient实例
     * @param request 请求对象
     * @return 响应对象,如果请求失败返回null
     */
    public static Response executeResponse(OkHttpClient client, Request request) {
        if (client == null || request == null) {
            log.error("OkHttpClient或Request为空");
            return null;
        }
        
        try {
            return client.newCall(request).execute();
        } catch (IOException e) {
            log.error("请求异常,URL: {}", request.url(), e);
            throw new RuntimeException("HTTP请求异常: " + e.getMessage(), e);
        }
    }

    /**
     * 构建GET请求
     * 
     * @param url 请求URL
     * @param headers 请求头
     * @return 请求对象
     */
    public static Request buildGetRequest(String url, Map<String, String> headers) {
        Request.Builder builder = new Request.Builder().url(url);
        if (headers != null && !headers.isEmpty()) {
            headers.forEach(builder::addHeader);
        }
        return builder.build();
    }

    /**
     * 构建POST请求(JSON格式)
     * 
     * @param url 请求URL
     * @param jsonBody JSON请求体
     * @param headers 请求头
     * @return 请求对象
     */
    public static Request buildPostJsonRequest(String url, String jsonBody, Map<String, String> headers) {
        RequestBody body = RequestBody.create(
                StringUtils.isBlank(jsonBody) ? "" : jsonBody, 
                JSON
        );
        
        Request.Builder builder = new Request.Builder()
                .url(url)
                .post(body);
        
        if (headers != null && !headers.isEmpty()) {
            headers.forEach(builder::addHeader);
        }
        
        return builder.build();
    }

    /**
     * 构建POST请求(表单格式)
     * 
     * @param url 请求URL
     * @param formParams 表单参数
     * @param headers 请求头
     * @return 请求对象
     */
    public static Request buildPostFormRequest(String url, Map<String, String> formParams, Map<String, String> headers) {
        FormBody.Builder formBuilder = new FormBody.Builder();
        
        if (formParams != null && !formParams.isEmpty()) {
            formParams.forEach(formBuilder::add);
        }
        
        RequestBody body = formBuilder.build();
        
        Request.Builder builder = new Request.Builder()
                .url(url)
                .post(body);
        
        if (headers != null && !headers.isEmpty()) {
            headers.forEach(builder::addHeader);
        }
        
        return builder.build();
    }
}

 

你好:我的2025