OKhttpClient 简单使用总结「建议收藏」

http优化,由httpClient改为OKHttpClient,研究了一下,网上资料不多大部分是安卓的,就着httpClient的入参简单写了一个公共方法,因为上一层使用了hystrix,就没有使用异步调用。后期看业务需要增加OKHttp的拦截和其他特性。注意请求timeout报java.io.InterruptedIOException:threadinterrupted异常,希望最新…

大家好,又见面了,我是你们的朋友全栈君。

http优化,由httpClient改为OKHttpClient,研究了一下,网上资料不多大部分是安卓的,就着httpClient的入参简单写了一个公共方法,因为上一层使用了hystrix,就没有使用异步调用。后期看业务需要增加OKHttp的拦截和其他特性。

注意请求time out 报java.io.InterruptedIOException: thread interrupted异常,希望最新版本能优化吧

后面加了一个网上找的比较全面的demo,包括了熔断配置。

参考资料:

官方介绍

github源码

OkHttp使用进阶 译自OkHttp Github官方教程

官方中文文档

OkHttp使用介绍

<!-- 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

}

下面是其他资料得到了配置,比我写的更详细

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/127500.html原文链接:https://javaforall.cn

【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛

【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...

(0)


相关推荐

  • linux下杀死某个进程_shell脚本获取进程号并杀死进程

    linux下杀死某个进程_shell脚本获取进程号并杀死进程在做项目的时候经常会出现程序死机、锁死、无响应等情况,这时候就需要找到程序相应的进程将其杀掉即可。步骤如下:1.定位进程top命令:可以实时动态地查看系统的整体运行情况,是一个综合了多方信息监测系统性能和运行信息的实用工具。通过top命令所提供的互动式界面,用热键可以管理。输入top后可以看到如下的界面,实时显示进程情况。ps命令:processstatus的简称,用于报告当…

  • SQL Server 存储过程

    SQL Server 存储过程

  • 什么是是JAVA构造函数

    什么是是JAVA构造函数每创建一个类的实例都去初始化它的所有变量是乏味的。如果一个对象在被创建时就完成了所有的初始工作,将是简单的和简洁的。因此,Java在类里提供了一个特殊的成员函数,叫做构造函数(Constructor)。一个构造函数是对象被创建时初始对象的成员函数。它具有和它所在的类完全一样的名字。一旦定义好一个构造函数,创建对象时就会自动调用它。构造函数没有返回类型,即使是void类型也没有。这是因为…

  • 交换芯片架构 (一)「建议收藏」

    交换芯片架构 (一)「建议收藏」交换芯片由GE/XE接口(MAC/PHY)模块、CPU接口模块、输入输出匹配/修改模块、MMU模块、L2转发模块、L3转发模块、安全模块、流分类模块等模块组成,其结构如图1所示:                                                   图1 交换芯片的组成56504包含24个GE端口,4个10G端口,10G端口既可以用于堆叠【什么

  • Spring StoredProcedure Cursor 使用

    Spring StoredProcedure Cursor 使用JavaCodeimportjava.sql.ResultSet;importjava.sql.SQLException;importjava.text.DateFormat;importjava.text.SimpleDateFormat;importjava.util.HashMap;importjava.util.List;importjava.util.

发表回复

您的电子邮箱地址不会被公开。

关注全栈程序员社区公众号