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. SVN—使用总结

    SVN使用教程总结 为什么要使用SVN? 在程序的编写过程中,每个程序员都会负责开发一个或多个模块,且开发中会生成很多不同的版本, 这就需要程序员有效的管理代码,在需要的时候可以迅速,准确取出相应的版 ...

  2. VS 统计整个项目总的代码行数

    vs如何快速统计项目总代码行数呢,如下: vs编辑 | 查找和替换 | 在文件中查找 查找选项选 选择正则表达式 ^b*[^:b#/]+.*$ 设置如下:  结果在查找结果的最后一行,如下 

  3. <2>基本表达式和语句

    1.基本表达式 1: =, +, -, *, /, 赋值,加减剩除; lua 没有 c/c++的缩写表达式 += -= *=, ++, --; 2: () 改变运算的优先级; 3: 字符串对象加法.. ...

  4. steam Depot 生成与应用脚本

    Depot 生成脚本 首先为您上传的每个 Depot 创建一个 Depot 生成脚本.从复制 depot_build_1001.vdf 脚本开始,并按将上传的 Depot ID 命名. Depot 生 ...

  5. 09 查找列表中元素,移除每个元素的空格,并查找以a或A开头并且以c结尾的所有元素

    li = ["alex"," aric","Alex","Tony","rain"]for i in ...

  6. CSS选择符-----属性选择符

       Element[att] 选择具有att属性的E元素 <!DOCTYPE html> <html> <head> <meta charset=" ...

  7. python 查询文本文件的层次

    I/O系统有一系列的层次构建而成 下面是操作一个文本文件的例子来查看这种层次 >>> f = open('sample.txt','w') >>> f <_i ...

  8. numpy数学数据处理

    数学和统计方法 sum 对数组中全部或某轴向的元素求和.零长度的数组的sum为0. mean 算术平均数.零长度的数组的mean为NaN. import numpy as np import nump ...

  9. grouping sets 的使用

    grouping sets 可以用于在计算分组聚合函数值的同时计算合计值 -- 查询结果group_id为NULL的那一行即为合计值 select group_id , count(distinct ...

  10. 听 Fabien Potencier 谈Symfony2 之 《What is Dependency Injection ?》

    听 Fabien Potencier 谈Symfony2 之 <What is Dependency Injection ?>   什么是依赖注入?从PHP实现角度来分析依赖注入,因为PH ...