OKhttpClient 簡單使用總結

RyanAce1988發表於2024-11-22
<!-- okhttp -->

<dependency>

   <groupId>com.squareup.okhttp3</groupId>

  <artifactId>okhttp</artifactId>

   <version>3.6.0</version>

</dependency>

<!-- okhttp /-->

@Service
public class OKHttpClient implements InitializingBean{
    private static int DEFAULT_READ_TIMEOUT_MILLIS = 500;
    private static int DEFAULT_CONNECT_TIMEOUT_MILLIS = 500;
    private static int DEFAULT_WRITE_TIMEOUT_MILLIS = 500;

    private OkHttpClient client;

    /**
     * 處理post請求,相容原httpClient請求
     * @param baseUrl
     * @param url
     * @param nvp
     * @param headers
     * @return
     * @throws Exception
     */
    public String post(String baseUrl, String url, List<NameValuePair> nvp, Header... headers)
            throws Exception {
        //Request build物件
        Request.Builder builder = getBuilder(baseUrl, url);
        //處理headers
        doHeaders(builder, headers);
        //處理請求引數
        doPostRequestBody(builder, nvp);
        //建立Request
        Request request = builder.build();
        //同步請求並獲取Response
        Response response = client.newCall(request).execute();
        //校驗並返回
        if (response.isSuccessful()) {
            return response.body().string();
        } else {
            throw new IOException("OKHttpClientApi post response: " + response);
        }
    }

    /**
     * 處理get請求,相容原httpClient請求
     * @param baseUrl
     * @param url
     * @param nvp
     * @param headers
     * @param cookies
     * @return
     * @throws Exception
     */
    public String get(String baseUrl, String url, List<NameValuePair> nvp, List<Header> headers, List<Cookie> cookies)
            throws Exception {
        //Request build物件,get請求沒有method方法,預設是PUT方式請求,直接在URL做引數處理
        Request.Builder builder = getBuilder(baseUrl, url + "?" + EntityUtils.toString(new UrlEncodedFormEntity(nvp, "UTF-8")));
        builder.get();
        //處理headers
        doHeaders(headers, builder);
        //建立Request
        Request request = builder.build();
        //處理cookies
        doCookies(cookies, request, client);
        //同步請求並獲取Response
        Response response = client.newCall(request).execute();
        //校驗並返回
         if (response.isSuccessful()) {
            return response.body().string();
        } else {
            throw new IOException("OKHttpClientApi get response: " + response);
        }
    }

    /**
     * post請求引數寫入Request.Builder
     * @param builder
     * @param nvp
     */
    private void doPostRequestBody(Request.Builder builder, List<NameValuePair> nvp) {
        FormBody.Builder bodyBuilder = new FormBody.Builder();
        if (!CollectionUtils.isEmpty(nvp)) {
            for (NameValuePair bean : nvp) {
                bodyBuilder.add(bean.getName(), bean.getValue());
            }
            builder.post(bodyBuilder.build());
        }else {
            builder.post(null);
        }
    }

    /**
     * 獲取Request.Builder
     * @param baseUrl
     * @param url
     * @return
     */
    private Request.Builder getBuilder(String baseUrl, String url) {
        return new Request.Builder().url(String.format("%s%s", baseUrl, url));
    }

    /**
     * 處理請求cookies
     * @param cookies
     * @param request
     * @param client
     */
    private void doCookies(List<Cookie> cookies, Request request, OkHttpClient client) {
        if (!CollectionUtils.isEmpty(cookies)) {
            client.cookieJar().saveFromResponse(request.url(), convertCookies(cookies));
        }
    }

    /**
     * 處理請求headers
     * @param headers
     * @param builder
     */
    private void doHeaders(List<Header> headers, Request.Builder builder) {
        if (!CollectionUtils.isEmpty(headers)) {
            Headers.Builder headeBuilder = new Headers.Builder();
            for (Header header : headers) {
                headeBuilder.add(header.getName(), header.getValue());
            }
            builder.headers(headeBuilder.build());
        }
    }

    /**
     * 處理請求headers
     * @param headers
     * @param builder
     */
    private void doHeaders(Request.Builder builder, Header[] headers) {
        if (headers != null && headers.length > 0) {
            Headers.Builder headeBuilder = new Headers.Builder();
            for (Header header : headers) {
                headeBuilder.add(header.getName(), header.getValue());
            }
            builder.headers(headeBuilder.build());
        }
    }

    /**
     * cookie轉化
     * @param cookies
     * @return
     */
    private List<okhttp3.Cookie> convertCookies(List<Cookie> cookies) {
        List<okhttp3.Cookie> list = new ArrayList<>();
        okhttp3.Cookie.Builder builder;
        for (Cookie cookie : cookies) {
            builder = new okhttp3.Cookie.Builder();
            builder.name(cookie.getName())
                   .domain(cookie.getDomain())
                   .expiresAt(cookie.getExpiryDate().getTime())
                   .path(cookie.getPath())
                   .value(cookie.getValue());
            if (cookie.isSecure()) {
                builder.secure();
            }
            list.add(builder.build());
        }
        return list;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        client = new OkHttpClient.Builder()
                .connectTimeout(DEFAULT_CONNECT_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS)
                .readTimeout(DEFAULT_READ_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS)
                .writeTimeout(DEFAULT_WRITE_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS)
                .build();
    }
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Map;
import java.util.concurrent.TimeUnit;


/**
 * 基於okhttp 的 httpclient 框架
 *
 * @author lixing
 */
@Component
public class OkHttpProxy implements InitializingBean {

    private final static Logger LOGGER = LoggerFactory.getLogger(OkHttpProxy.class);

    @Autowired
    OkHttpConfig okHttpConfig;

    private static OkHttpClient okHttpClient;

    private int maxIdleConnections;
    private long keepAliveDuration;
    private long connectTimeout;
    private long readTimeout;

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

    @PostConstruct
    public void init() {
        connectTimeout = okHttpConfig.getOkhttpConnectTimeout() == null ? 0 : Integer.parseInt(okHttpConfig.getOkhttpConnectTimeout());
        readTimeout = okHttpConfig.getOkhttpReadTimeout() == null ? 0 : Integer.parseInt(okHttpConfig.getOkhttpReadTimeout());
        maxIdleConnections = okHttpConfig.getOkhttpMaxIdleConnections() == null ? 0 : Integer.parseInt(okHttpConfig.getOkhttpMaxIdleConnections());
        keepAliveDuration = okHttpConfig.getOkhttpKeepAliveDuration() == null ? 0 : Integer.parseInt(okHttpConfig.getOkhttpKeepAliveDuration());
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        if (0 != connectTimeout) {
            builder.connectTimeout(connectTimeout, TimeUnit.SECONDS);
        }
        if (0 != readTimeout) {
            builder.readTimeout(readTimeout, TimeUnit.SECONDS);
        }
        if (0 != maxIdleConnections && 0 != keepAliveDuration) {
            ConnectionPool pool = new ConnectionPool(maxIdleConnections, keepAliveDuration, TimeUnit.SECONDS);
            builder.connectionPool(pool);
        }
        okHttpClient = builder.build();
    }


    public String doGet(String url, String queryString, Map<String, String> headerMap) throws Exception {
        Response response ;
        Request.Builder reqBuilder = new Request.Builder();
        this.prepareHeader(headerMap, reqBuilder);
        Request getRequest = reqBuilder.url(url + "?" + queryString).get().build();
        response = okHttpClient.newCall(getRequest).execute();
        this.errorResponseLog(response, url);
        return response.body().string();
    }

    public String doPost(String url, String queryString, Map<String, String> paramMap, Map<String, String> headerMap) throws Exception {
        Response response ;
        Request.Builder reqBuilder = new Request.Builder();
        if (headerMap != null) {
            for (String key : headerMap.keySet()) {
                reqBuilder.addHeader(key, headerMap.get(key));
            }
        }
        FormBody.Builder formBodyBuilder = new FormBody.Builder();
        if (paramMap != null) {
            for (String key : paramMap.keySet()) {
                formBodyBuilder.add(key, paramMap.get(key));
            }
        }
        RequestBody body = formBodyBuilder.build();
        if (queryString != null) {
            url = url + "?" + queryString;
        }
        Request postRequest = reqBuilder.url(url).post(body).build();
        response = okHttpClient.newCall(postRequest).execute();
        this.errorResponseLog(response, url);
        return response.body().string();
    }

    public String doMix(String url, String queryString, Map<String, String> headerMap) throws Exception {
        Response response ;
        Request.Builder reqBuilder = new Request.Builder();
        this.prepareHeader(headerMap, reqBuilder);
        FormBody.Builder formBodyBuilder = new FormBody.Builder();
        RequestBody body = formBodyBuilder.build();
        Request postRequest = reqBuilder.url(url + "?" + queryString).post(body).build();
        response = okHttpClient.newCall(postRequest).execute();
        this.errorResponseLog(response, url);
        return response.body().string();
    }

    public String doMix(String url, String queryString, Map<String, String> bodyParamMap, Map<String, String> headerMap) throws Exception {
        Response response ;
        Request.Builder reqBuilder = new Request.Builder();
        this.prepareHeader(headerMap, reqBuilder);
        FormBody.Builder formBodyBuilder = new FormBody.Builder();
        if (bodyParamMap != null) {
            for (String key : bodyParamMap.keySet()) {
                formBodyBuilder.add(key, headerMap.get(key));
            }
        }
        RequestBody body = formBodyBuilder.build();
        Request postRequest = reqBuilder.url(url + "?" + queryString).post(body).build();
        response = okHttpClient.newCall(postRequest).execute();
        this.errorResponseLog(response, url);
        return response.body().string();
    }

    public String doPostByJson(String url, String json, Map<String, String> headerMap) throws Exception {
        Response response ;
        Request.Builder builder = new Request.Builder().url(url);
        this.prepareHeader(headerMap, builder);
        RequestBody requestBody = RequestBody.create(JSON, json);
        Request request = builder.post(requestBody).build();
        response = okHttpClient.newCall(request).execute();
        this.errorResponseLog(response, url);
        return response.body().string();
    }


    private void prepareHeader(Map<String, String> headerMap, Request.Builder builder) {
        if (headerMap != null) {
            for (String key : headerMap.keySet()) {
                builder.addHeader(key, headerMap.get(key));
            }
        }
    }

    private void errorResponseLog(Response response, String url) throws Exception {
        if (response == null) {
            LOGGER.error("okhttpclient call fail,url={},  message=response is null", url);
            throw new Exception(String.format("http call fail,url=%s,  status=null", url));
        }
        if (!response.isSuccessful()) {
            LOGGER.error("okhttpclient call fail,url={},  message={}", url, response.body().string());
            throw new Exception(String.format("http call fail,url=%s,  status=%s", url, response.code()));
        }
    }
}

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

/**
 * okHttp config
 *
 * @author huangbingchi on 2018/1/25 下午1:46
 * @version 1.0.0
 */
@Configuration
public class OkHttpConfig implements java.io.Serializable {

    @Value("${okhttp.connectTimeout}")
    private String okhttpConnectTimeout;

    @Value("${okhttp.readTimeout}")
    private String okhttpReadTimeout;

    @Value("${okhttp.keepAliveDuration}")
    private String okhttpKeepAliveDuration;

    @Value("${okhttp.maxIdleConnections}")
    private String okhttpMaxIdleConnections;

    @Value("${okhttp.hystrix.threshold}")
    private String hystrixThreshold;

    @Value("${okhttp.hystrix.sleep}")
    private String hystrixSleep;

    @Value("${okhttp.hystrix.threshold.percentage}")
    private String hystrixThresholdPercentage;

    @Value("${okhttp.hystrix.threads}")
    private String hystrixThreads;

    @Value("${okhttp.hystrix.fallback.accepts}")
    private String hystrixFallbackAccepts;

#okhttp配置
okhttp.connectTimeout=1
okhttp.readTimeout=1
okhttp.keepAliveDuration=0
okhttp.maxIdleConnections=0
#okhttp熔斷配置
okhttp.hystrix.threshold=20
okhttp.hystrix.sleep=20000
okhttp.hystrix.threshold.percentage=50
okhttp.hystrix.threads=30
okhttp.hystrix.fallback.accepts=500

相關文章