1.添加pom.xml依赖

        <dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>3.6.</version>
</dependency>

2.配置类

import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.concurrent.TimeUnit;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import okhttp3.ConnectionPool;
import okhttp3.OkHttpClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; /**
* Created by qhong on 2018/7/3 16:52
**/
@Configuration
public class OkHttpConfig { @Bean
public X509TrustManager x509TrustManager() {
return new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[];
}
};
}
@Bean
public SSLSocketFactory sslSocketFactory() {
try {
//信任任何链接
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, new TrustManager[]{x509TrustManager()}, new SecureRandom());
return sslContext.getSocketFactory();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
}
return null;
}
/**
* Create a new connection pool with tuning parameters appropriate for a single-user application.
* The tuning parameters in this pool are subject to change in future OkHttp releases. Currently
*/
@Bean
public ConnectionPool pool() {
return new ConnectionPool(, , TimeUnit.MINUTES);
}
@Bean
public OkHttpClient okHttpClient() {
return new OkHttpClient.Builder()
.sslSocketFactory(sslSocketFactory(), x509TrustManager())
.retryOnConnectionFailure(false)//是否开启缓存
.connectionPool(pool())//连接池
.connectTimeout(10L, TimeUnit.SECONDS)
.readTimeout(10L, TimeUnit.SECONDS)
.build();
}
}

3.工具类:

import java.util.Iterator;
import java.util.Map;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; /**
* Created by qhong on 2018/7/3 16:55
**/
public class OkHttpUtil{ private static final Logger logger = LoggerFactory.getLogger(OkHttpUtil.class); /**
* 根据map获取get请求参数
* @param queries
* @return
*/
public static StringBuffer getQueryString(String url,Map<String,String> queries){
StringBuffer sb = new StringBuffer(url);
if (queries != null && queries.keySet().size() > ) {
boolean firstFlag = true;
Iterator iterator = queries.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry entry = (Map.Entry<String, String>) iterator.next();
if (firstFlag) {
sb.append("?" + entry.getKey() + "=" + entry.getValue());
firstFlag = false;
} else {
sb.append("&" + entry.getKey() + "=" + entry.getValue());
}
}
}
return sb;
} /**
* 调用okhttp的newCall方法
* @param request
* @return
*/
private static String execNewCall(Request request){
Response response = null;
try {
OkHttpClient okHttpClient = SpringUtils.getBean(OkHttpClient.class);
response = okHttpClient.newCall(request).execute();
int status = response.code();
if (response.isSuccessful()) {
return response.body().string();
}
} catch (Exception e) {
logger.error("okhttp3 put error >> ex = {}", ExceptionUtils.getStackTrace(e));
} finally {
if (response != null) {
response.close();
}
}
return "";
} /**
* get
* @param url 请求的url
* @param queries 请求的参数,在浏览器?后面的数据,没有可以传null
* @return
*/
public static String get(String url, Map<String, String> queries) {
StringBuffer sb = getQueryString(url,queries);
Request request = new Request.Builder()
.url(sb.toString())
.build();
return execNewCall(request);
} /**
* post
*
* @param url 请求的url
* @param params post form 提交的参数
* @return
*/
public static String postFormParams(String url, Map<String, String> params) {
FormBody.Builder builder = new FormBody.Builder();
//添加参数
if (params != null && params.keySet().size() > ) {
for (String key : params.keySet()) {
builder.add(key, params.get(key));
}
}
Request request = new Request.Builder()
.url(url)
.post(builder.build())
.build();
return execNewCall(request);
} /**
* Post请求发送JSON数据....{"name":"zhangsan","pwd":"123456"}
* 参数一:请求Url
* 参数二:请求的JSON
* 参数三:请求回调
*/
public static String postJsonParams(String url, String jsonParams) {
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonParams);
Request request = new Request.Builder()
.url(url)
.post(requestBody)
.build();
return execNewCall(request);
} /**
* Post请求发送xml数据....
* 参数一:请求Url
* 参数二:请求的xmlString
* 参数三:请求回调
*/
public static String postXmlParams(String url, String xml) {
RequestBody requestBody = RequestBody.create(MediaType.parse("application/xml; charset=utf-8"), xml);
Request request = new Request.Builder()
.url(url)
.post(requestBody)
.build();
return execNewCall(request);
}
}

https://miaoxinwei.github.io/2017/04/21/spring-%E9%9B%86%E6%88%90-okhttp3/

https://blog.csdn.net/wangh92/article/details/79714375

https://www.programcreek.com/java-api-examples/?code=hjw541988478/OkHttpTutorial/OkHttpTutorial-master/app/src/main/java/in/harvestday/okhttpdemo/OkHttpUtil.java

https://github.com/guozhengXia/OkHttpUtils

https://github.com/hongyangAndroid/okhttputils

SpringBoot 使用okhttp3的更多相关文章

  1. SpringBoot编写自定义的starter 专题

    What’s in a name All official starters follow a similar naming pattern; spring-boot-starter-*, where ...

  2. SpringBoot系列: RestTemplate 快速入门

    ====================================相关的文章====================================SpringBoot系列: 与Spring R ...

  3. 第二十七章 springboot + zipkin(brave-okhttp实现)

    本文截取自:http://blog.csdn.net/liaokailin/article/details/52077620 一.前提 1.zipkin基本知识:附8 zipkin 2.启动zipki ...

  4. 【第二十七章】 springboot + zipkin(brave-okhttp实现)

    本文截取自:http://blog.csdn.net/liaokailin/article/details/52077620 一.前提 1.zipkin基本知识:附8 zipkin 2.启动zipki ...

  5. springboot 配置jpa启动报Error processing condition on org.springframework.boot.autoconfigure.data.web.SpringDataWebAutoConfiguration.pageableCustomizer

    springboot +gradle 配置jpa启动报Error processing condition on org.springframework.boot.autoconfigure.data ...

  6. SpringBoot集成Zipkin实现分布式全链路监控

    目录 Zipkin 简介 Springboot 集成 Zipkin 安装启动 zipkin 版本说明 项目结构 工程端口分配 引入 Maven 依赖 配置文件.收集器的设置 编写 Controller ...

  7. Spring Cloud Feign 总结问题,注意点,性能调优,切换okhttp3

    ### Feign常见问题总结 **FeignClient接口如使用`@PathVariable` ,必须指定value属性** ```java //在一些早期版本中, @PathVariable(& ...

  8. springboot 整合 freemarker

    springboot 整合 freemarker 依赖 <parent> <groupId>org.springframework.boot</groupId> & ...

  9. springboot装配OkHttp组件

    在SpringBoot应用中,发送Http通常我们使用RestTemplate,但有部分组件底层是使用OkHttp进行Http的操作,而且OKHttp也是一个很优秀的HTTP组件. RestTempa ...

随机推荐

  1. Android -- RecyclerView实现左滑删除

    1,在实际项目中我们常常有对一个列表进行滑删除操作,使用我们昨天的ItemTouchHelper其实也可以实现简单的实现这个功能,先来看一下使用ItemTouchHelper来实现的效果: 2,从上面 ...

  2. Yii2 Gridview查询关联筛选

  3. Keras中使用LSTM层时设置的units参数是什么

    https://www.zhihu.com/question/64470274 http://colah.github.io/posts/2015-08-Understanding-LSTMs/ ht ...

  4. Another Meaning (KMP + DP)

    先用KMP重叠匹配求出各个匹配成功的尾串位置.然后利用DP去求,那转移方程应该是等于 上一个状态 (无法匹配新尾巴) 上一个状态 + 以本次匹配起点为结尾的状态(就是说有了新的位置) + 1 (单单一 ...

  5. 【Oozie学习之一】Oozie

    环境 虚拟机:VMware 10 Linux版本:CentOS-6.5-x86_64 客户端:Xshell4 FTP:Xftp4 jdk8 CM5.4 一.简介Oozie由Cloudera公司贡献给A ...

  6. OS Tools-GO富集分析工具的使用与解读详细教程

    我们的云平台上的GO富集分析工具,需要输入的文件表格和参数很简单,但很多同学都不明白其中的原理与结果解读,这个帖子就跟大家详细解释~ 一.GO富集介绍:       Gene Ontology(简称G ...

  7. win10安装mongodb-win32-x86_64-2008plus-ssl-3.4.10-signed

    1.下载mongodb在windows下的安装文件 首先去官网https://www.mongodb.com/download-center?jmp=nav#community下载安装文件.mongo ...

  8. 使用yaml+groovy实现Java代码可配置化

    背景与目标 在使用函数接口和枚举实现配置式编程(Java与Scala实现),使用了函数接口和枚举实现了配置式编程.读者可先阅读此文,再来阅读本文. 有时,需要将一些业务逻辑,使用配置化的方式抽离出来, ...

  9. django 常用方法总结 < 手写分页-上传头像-redis缓存,排行 ...>

    1.不使用自带模块<Paginator>的手写分页功能views.pydef post_list(request): page = request.GET.get('page', 1) # ...

  10. Django框架----权限管理(设计分析以及具体细节)

    说起权限我们大家都知道,不一样的角色会有不一样的权限.比如就像学生管理系统一样,管理员,老师,学生之间的权限都是不一样的,那么展示的页面也是不一样的.所以,我们现在来看看具体操作. 目标:生成一个独立 ...