spring okhttp3
准备工作
在pom.xml文件中增加以下依赖
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>3.6.0</version>
</dependency>
书写配置类
用@Configuration注解该类,等价与XML中配置beans;用@Bean标注方法等价于XML中配置bean。
@Configuration
@Configuration
public class OkHttpConfiguration {
@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[0];
}
};
}
@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(200, 5, TimeUnit.MINUTES);
}
@Bean
public OkHttpClient okHttpClient() {
return new OkHttpClient.Builder()
.sslSocketFactory(sslSocketFactory(), x509TrustManager())
.retryOnConnectionFailure(false)//是否开启缓存
.connectionPool(pool())//连接池
.connectTimeout(100, TimeUnit.SECONDS)//设置链接超时
.writeTimeout(100, TimeUnit.SECONDS)// 设置写数据超时
.readTimeout(100, TimeUnit.SECONDS)// 设置读数据超时
.build();
}
}
工具类
自己写的工具类,比较简单,不是REST风格
@Component
public class OkHttpUtil {
private static final Logger logger = LoggerFactory.getLogger(OkHttpUtil.class);
@Resource
private OkHttpClient okHttpClient;
/**
* get
*
* @param url 请求的url
* @param queries 请求的参数,在浏览器?后面的数据,没有可以传null
* @return
*/
public String get(String url, Map<String, String> queries) {
String responseBody = "";
StringBuffer sb = new StringBuffer(url);
if (queries != null && queries.keySet().size() > 0) {
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());
}
}
}
Request request = new Request
.Builder()
.url(sb.toString())
.build();
Response response = null;
try {
response = okHttpClient.newCall(request).execute();
int status = response.code();
if (status == 200) {
return response.body().string();
}
} catch (Exception e) {
logger.error("okhttp put error >> ex = {}", ExceptionUtils.getStackTrace(e));
} finally {
if (response != null) {
response.close();
}
}
return responseBody;
}
/**
* post
*
* @param url 请求的url
* @param params post form 提交的参数
* @return
*/
public String post(String url, Map<String, String> params) {
String responseBody = "";
FormBody.Builder builder = new FormBody.Builder();
//添加参数
if (params != null && params.keySet().size() > 0) {
for (String key : params.keySet()) {
builder.add(key, params.get(key));
}
}
Request request = new Request
.Builder()
.url(url)
.post(builder.build())
.build();
Response response = null;
try {
response = okHttpClient.newCall(request).execute();
int status = response.code();
if (status == 200) {
return response.body().string();
}
} catch (Exception e) {
logger.error("okhttp post error >> ex = {}", ExceptionUtils.getStackTrace(e));
} finally {
if (response != null) {
response.close();
}
}
return responseBody;
}
/**
* post 上传文件
*
* @param url
* @param params
* @param fileType
* @return
*/
public String postFile(String url, Map<String, Object> params, String fileType) {
String responseBody = "";
MultipartBody.Builder builder = new MultipartBody.Builder();
//添加参数
if (params != null && params.keySet().size() > 0) {
for (String key : params.keySet()) {
if (params.get(key) instanceof File) {
File file = (File) params.get(key);
builder.addFormDataPart(key, file.getName(), RequestBody.create(MediaType.parse(fileType), file));
continue;
}
builder.addFormDataPart(key, params.get(key).toString());
}
}
Request request = new Request
.Builder()
.url(url)
.post(builder.build())
.build();
Response response = null;
try {
response = okHttpClient.newCall(request).execute();
int status = response.code();
if (status == 200) {
return response.body().string();
}
} catch (Exception e) {
logger.error("okhttp postFile error >> ex = {}", ExceptionUtils.getStackTrace(e));
} finally {
if (response != null) {
response.close();
}
}
return responseBody;
}
}
okhttp 一般的util工具
import okhttp3.*;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import java.io.File;
import java.util.Iterator;
import java.util.Map; public class OkHttpUtil{
private static final Logger logger = LoggerFactory.getLogger(OkHttpUtil.class); /**
* get
* @param url 请求的url
* @param queries 请求的参数,在浏览器?后面的数据,没有可以传null
* @return
*/
public static String get(String url, Map<String, String> queries) {
String responseBody = "";
StringBuffer sb = new StringBuffer(url);
if (queries != null && queries.keySet().size() > 0) {
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());
}
}
}
Request request = new Request.Builder()
.url(sb.toString())
.build();
Response response = null;
try {
OkHttpClient okHttpClient = new OkHttpClient();
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 responseBody;
} /**
* post
*
* @param url 请求的url
* @param params post form 提交的参数
* @return
*/
public static String post(String url, Map<String, String> params) {
String responseBody = "";
FormBody.Builder builder = new FormBody.Builder();
//添加参数
if (params != null && params.keySet().size() > 0) {
for (String key : params.keySet()) {
builder.add(key, params.get(key));
}
}
Request request = new Request.Builder()
.url(url)
.post(builder.build())
.build();
Response response = null;
try {
OkHttpClient okHttpClient = new OkHttpClient();
response = okHttpClient.newCall(request).execute();
int status = response.code();
if (response.isSuccessful()) {
return response.body().string();
}
} catch (Exception e) {
logger.error("okhttp3 post error >> ex = {}", ExceptionUtils.getStackTrace(e));
} finally {
if (response != null) {
response.close();
}
}
return responseBody;
} /**
* get
* @param url 请求的url
* @param queries 请求的参数,在浏览器?后面的数据,没有可以传null
* @return
*/
public static String getForHeader(String url, Map<String, String> queries) {
String responseBody = "";
StringBuffer sb = new StringBuffer(url);
if (queries != null && queries.keySet().size() > 0) {
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());
}
}
}
Request request = new Request.Builder()
.addHeader("key", "value")
.url(sb.toString())
.build();
Response response = null;
try {
OkHttpClient okHttpClient = new OkHttpClient();
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 responseBody;
} /**
* Post请求发送JSON数据....{"name":"zhangsan","pwd":"123456"}
* 参数一:请求Url
* 参数二:请求的JSON
* 参数三:请求回调
*/
public static String postJsonParams(String url, String jsonParams) {
String responseBody = "";
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonParams);
Request request = new Request.Builder()
.url(url)
.post(requestBody)
.build();
Response response = null;
try {
OkHttpClient okHttpClient = new OkHttpClient();
response = okHttpClient.newCall(request).execute();
int status = response.code();
if (response.isSuccessful()) {
return response.body().string();
}
} catch (Exception e) {
logger.error("okhttp3 post error >> ex = {}", ExceptionUtils.getStackTrace(e));
} finally {
if (response != null) {
response.close();
}
}
return responseBody;
} /**
* Post请求发送xml数据....
* 参数一:请求Url
* 参数二:请求的xmlString
* 参数三:请求回调
*/
public static String postXmlParams(String url, String xml) {
String responseBody = "";
RequestBody requestBody = RequestBody.create(MediaType.parse("application/xml; charset=utf-8"), xml);
Request request = new Request.Builder()
.url(url)
.post(requestBody)
.build();
Response response = null;
try {
OkHttpClient okHttpClient = new OkHttpClient();
response = okHttpClient.newCall(request).execute();
int status = response.code();
if (response.isSuccessful()) {
return response.body().string();
}
} catch (Exception e) {
logger.error("okhttp3 post error >> ex = {}", ExceptionUtils.getStackTrace(e));
} finally {
if (response != null) {
response.close();
}
}
return responseBody;
}
}
使用方法
@Resource
private OkHttpUtil okHttpUtil;
spring okhttp3的更多相关文章
- Spring Cloud Feign 总结问题,注意点,性能调优,切换okhttp3
### Feign常见问题总结 **FeignClient接口如使用`@PathVariable` ,必须指定value属性** ```java //在一些早期版本中, @PathVariable(& ...
- Spring Cloud feign使用okhttp3
指南 maven <dependency> <groupId>io.github.openfeign</groupId> <artifactId>fei ...
- Set up HTTP/2 server with Spring Boot 【基于Spring boot搭建http2.0服务器】
1. Server side With spring boot, we can set up a http server easily. Restcontroller make it easier t ...
- Spring Cloud项目中通过Feign进行内部服务调用发生401\407错误无返回信息的问题
问题描述 最近在使用Spring Cloud改造现有服务的工作中,在内部服务的调用方式上选择了Feign组件,由于服务与服务之间有权限控制,发现通过Feign来进行调用时如果发生了401.407错误时 ...
- Spring Cloud微服务笔记(五)Feign
Feign 一.Feign概述 Feign是一个声明式的Web Service客户端.在Spring Cloud 中使用Feign,可以做到 使用HTTP请求访问远程服务,就像调用本地方法一样,同时它 ...
- Spring FactoryBean应用
Spring 中有两种类型的Bean,一种是普通Bean,另一种是工厂Bean 即 FactoryBean.FactoryBean跟普通Bean不同,其返回的对象不是指定类的一个实例,而是该Facto ...
- Spring Cloud内置的Zuul过滤器详解
Spring Cloud默认为Zuul编写并启用了一些过滤器,这些过滤器有什么作用呢?我们不妨按照@EnableZuulServer.@EnableZuulProxy两个注解进行展开,相信大家对这两个 ...
- spring cloud连载第三篇补充之Zuul
由于Zuul的内容较多所以单独列出一篇来讲.全是干货,如果学到东西的,动动小手给点个推荐^_^ 谢谢! 1. Router and Filter: Zuul(路由和过滤:Zuul) 路由是微服务架构 ...
- idea+maven+spring+cxf创建webservice应用(二)生成客户端程序
idea+maven+spring+cxf创建webservice应用(二)生成客户端程序,以上一篇为基础"idea+maven+spring+cxf创建webservice应用" ...
随机推荐
- Windows跨域远程连接防火墙设置
按照正常的防火墙的设置,发现跨域远程依然不行,后来进过排除法发现 还需要打开icmpv4所有的协议,才可以
- Codeforces1076E. Vasya and a Tree(dfs+离线+动态维护前缀和)
题目链接:传送门 题目: E. Vasya and a Tree time limit per test seconds memory limit per test megabytes input s ...
- 洛谷P1357 花园(状态压缩 + 矩阵快速幂加速递推)
题目链接:传送门 题目: 题目描述 小L有一座环形花园,沿花园的顺时针方向,他把各个花圃编号为1~N(<=N<=^).他的环形花园每天都会换一个新花样,但他的花园都不外乎一个规则,任意相邻 ...
- some working learning总结学习(二)
2. 读取excel上的测试用例和结果,成json格式,最终存到access数据库 结果如下: { : { 'Req_ID': 'Fqqqqq/qqqqq', 'Case_ID': 'ATC_LvPw ...
- 前端 --- 5 BOM 和 DOM
一.BOM BOM(Browser Object Model)是指浏览器对象模型, 它使 JavaScript 有能力与浏览器进行“对话”. 1. window 对象 一些常用的Window方法: ( ...
- node 下less无法编译的问题
vue+less的项目中,npm run dev不通过,提示以下错误: These dependencies were not found: * !!vue-style-loader!css-load ...
- 公式推导:【BACF】
[BACF]: Kiani Galoogahi H, Fagg A, Lucey S. Learning Background-Aware Correlation Filters for Visual ...
- ASP.NET Core 2.0系列学习笔记-NLog日志配置文件
一.新建ASP.NET Core 2.0 MVC项目,使用NuGet在浏览中搜索:NLog.Web.AspNetCore,如下图所示: 二.在项目的根目录下新建一个xml类型的nlog.config文 ...
- Promise的实现原理
1.Promise 介绍 Promise类似一个事务管理器,将用户异步操作流程用流水的形式来表达,用来延迟deferred和异步asynchronous. 特点如下: (1)对象的状态不受外界影响 P ...
- Kafka介绍与消息队列
消息队列的好处: 消息队列(Message Queue) 消息: 网络中的两台计算机或者两个通讯设备之间传递的数据.例如说:文本.音乐.视频等内容. 队列:一种特殊的线性表(数据元素首尾相接),特殊之 ...