OkHttp3使用教程,实现get、post请求发送,自动重试,打印响应日志。
一、创建线程安全的okhttp单例
import service.NetworkIntercepter;
import service.RetryIntercepter;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit; public class HttpUtils {
private static final Logger LOGGER = LoggerFactory.getLogger(HttpUtils.class);
private static final int CONNECTION_TIME_OUT = 2000;//连接超时时间
private static final int SOCKET_TIME_OUT = 2000;//读写超时时间
private static final int MAX_IDLE_CONNECTIONS = 30;// 空闲连接数
private static final long KEEP_ALLIVE_TIME = 60000L;//保持连接时间 private OkHttpClient okHttpClient;
private volatile static HttpUtils httpUtils; public static HttpUtils getInstance(){
if(httpUtils == null){
synchronized (HttpUtils.class){
if(httpUtils == null){
httpUtils = new HttpUtils();
}
}
}
return httpUtils; }
public HttpUtils(){
ConnectionPool connectionPool = new ConnectionPool(MAX_IDLE_CONNECTIONS,KEEP_ALLIVE_TIME,TimeUnit.MILLISECONDS);
this.okHttpClient = new OkHttpClient()
.newBuilder()
.readTimeout(SOCKET_TIME_OUT, TimeUnit.MILLISECONDS)
.writeTimeout(SOCKET_TIME_OUT, TimeUnit.MILLISECONDS)
.connectionPool(connectionPool)
.retryOnConnectionFailure(false) //自动重连设置为false
.connectTimeout(CONNECTION_TIME_OUT,TimeUnit.MILLISECONDS)
.addInterceptor(new RetryIntercepter(2)) //重试拦截器2次
.addNetworkInterceptor(new NetworkIntercepter()) //网络拦截器,统一打印日志
.build();
}
}
重试拦截器:
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response; import java.io.IOException; public class RetryIntercepter implements Interceptor{
public int maxRetryCount;
private int count = 0;
public RetryIntercepter(int maxRetryCount) {
this.maxRetryCount = maxRetryCount;
} @Override
public Response intercept(Chain chain) throws IOException { return retry(chain);
} public Response retry(Chain chain){
Response response = null;
Request request = chain.request();
try {
response = chain.proceed(request);
while (!response.isSuccessful() && count < maxRetryCount) {
count++;
response = retry(chain);
}
}
catch (Exception e){
while (count < maxRetryCount){
count++;
response = retry(chain);
}
}
return response;
}
}
注意:两处while是因为如果请求中出现异常,也能进行重试,比如超时,后面会有例子。
网络拦截器,打印请求、响应时间、响应状态码,响应内容
import okhttp3.*;
import okio.Buffer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import java.io.IOException;
import java.nio.charset.Charset; public class NetworkIntercepter implements Interceptor{
private static Logger LOGGER = LoggerFactory.getLogger(NetworkIntercepter.class);
@Override
public Response intercept(Interceptor.Chain chain) {
long start = System.currentTimeMillis();
Response response=null;
String responseBody = null;
String responseCode = null;
String url = null;
String requestBody = null;
try {
Request request = chain.request();
url = request.url().toString();
requestBody = getRequestBody(request);
response = chain.proceed(request);
responseBody = response.body().string();
responseCode = String.valueOf(response.code());
MediaType mediaType = response.body().contentType();
response = response.newBuilder().body(ResponseBody.create(mediaType,responseBody)).build();
}
catch (Exception e){
LOGGER.error(e.getMessage());
}
finally {
long end = System.currentTimeMillis();
String duration = String.valueOf(end - start);
LOGGER.info("responseTime= {}, requestUrl= {}, params={}, responseCode= {}, result= {}",
duration, url,requestBody,responseCode,responseBody);
} return response;
} private String getRequestBody(Request request) {
String requestContent = "";
if (request == null) {
return requestContent;
}
RequestBody requestBody = request.body();
if (requestBody == null) {
return requestContent;
}
try {
Buffer buffer = new Buffer();
requestBody.writeTo(buffer);
Charset charset = Charset.forName("utf-8");
requestContent = buffer.readString(charset);
} catch (IOException e) {
e.printStackTrace();
}
return requestContent;
}
}
二、GET请求
1、带参数的get请求
/*
* 发送待url参数的get
*/
public String get(String url,Map<String,String> pathParams){
HttpUrl.Builder builder = HttpUrl.parse(url).newBuilder();
for(String key:pathParams.keySet()){
builder.addQueryParameter(key,pathParams.get(key) );
}
Request request = new Request.Builder()
.url(builder.build().toString())
.build();
return execute(request);
} private String execute(Request request){
String responseBody=null;
try {
Response response = okHttpClient.newCall(request).execute();
responseBody = response.body().string();
} catch (IOException |NullPointerException e) {
e.printStackTrace();
}
return responseBody;
}
测试:
String url = "http://localhost:8080/test/12346/query";
Map<String,String> params = new HashMap<>();
params.put("aaa","111");
params.put("bbb","222");
HttpUtils httpUtils = HttpUtils.getInstance();
httpUtils.get(url,params); 打印日志如下:
[main][2019-09-21 10:19:02.072] [INFO] [NetworkIntercepter.intercept:40] responseTime= 62, requestUrl= http://localhost:8080/test/12346/query?aaa=111&bbb=222, params=, responseCode= 200, result= {"result_code":"success","data":{"aaa":"111"},"path":"/test/12346/query"}
2、不带参数的get请求
测试:
String url = "http://localhost:8080/test/12346/query?ccc=1&ddd=2";
HttpUtils httpUtils = HttpUtils.getInstance();
httpUtils.get(url); 打印日志如下:
[main][2019-09-21 10:25:46.943] [INFO] [NetworkIntercepter.intercept:38] responseTime= 11, requestUrl= http://localhost:8080/test/12346/query?ccc=1&ddd=2, params=, responseCode= 200, result= {"result_code":"success","data":{"aaa":"111"},"path":"/test/12346/query"}
三、POST请求
1、post发送带url参数的json
/*
* post发送带url参数的json
*/
public String post(String url, Map<String,String> pathParams, String body){
RequestBody requestBody = RequestBody.
create(MediaType.parse("application/json;charset=utf-8"), body);
HttpUrl.Builder builder = HttpUrl.parse(url).newBuilder();
for(String key:pathParams.keySet()){
builder.addQueryParameter(key,pathParams.get(key) );
}
Request request = new Request.Builder()
.post(requestBody)
.url(builder.build().toString())
.build();
return execute(request);
}
测试:
Gson gson = new Gson();
String url = "http://localhost:8080/test/12346/query";
Map<String,String> params = new HashMap<>();
params.put("aaa","111");
params.put("bbb","222"); Map<String,Object> bodyMap = new HashMap<>();
bodyMap.put("name","zhangsan");
bodyMap.put("age",15);
HttpUtils httpUtils = HttpUtils.getInstance();
httpUtils.post(url,params,gson.toJson(bodyMap)); 打印日志
[main][2019-09-21 10:37:04.577] [INFO] [NetworkIntercepter.intercept:38] responseTime= 304, requestUrl= http://localhost:8080/test/12346/query?aaa=111&bbb=222, params={"name":"zhangsan","age":15}, responseCode= 200, result= {"result_code":"success","data":{"aaa":"111"},"path":"/test/12346/query"}
2、post发送json
/*
* post发送json
*/
public String post(String url,String body){
Map<String,String> pathParams = new HashMap<>();
return post(url,pathParams ,body );
}
测试:
Gson gson = new Gson();
String url = "http://localhost:8080/test/12346/query";
Map<String,Object> bodyMap = new HashMap<>();
bodyMap.put("name","zhangsan");
bodyMap.put("age",15);
HttpUtils httpUtils = HttpUtils.getInstance();
httpUtils.post(url,gson.toJson(bodyMap));
打印日志:
[main][2019-09-21 10:44:00.835] [INFO] [NetworkIntercepter.intercept:38] responseTime= 17, requestUrl= http://localhost:8080/test/12346/query, params={"name":"zhangsan","age":15}, responseCode= 200, result= {"result_code":"success","data":{"aaa":"111"},"path":"/test/12346/query"}
3、post发送表单
/*
* post发送表单
*/
public String post(String url, Map<String,String> pathParams){
FormBody.Builder formBodyBuilder = new FormBody.Builder();
HttpUrl.Builder builder = HttpUrl.parse(url).newBuilder();
for(String key:pathParams.keySet()){
formBodyBuilder.add(key,pathParams.get(key) );
}
RequestBody requestBody = formBodyBuilder.build();
Request request = new Request.Builder()
.post(requestBody)
.url(builder.build().toString())
.build();
return execute(request);
}
测试:
String url = "http://localhost:8080/test/12346/query";
Map<String,String> params = new HashMap<>();
params.put("aaa","111");
params.put("bbb","222");
HttpUtils httpUtils = HttpUtils.getInstance();
httpUtils.post(url,params); 打印日志:
[main][2019-09-21 10:49:54.136] [INFO] [NetworkIntercepter.intercept:38] responseTime= 21, requestUrl= http://localhost:8080/test/12346/query, params=aaa=111&bbb=222, responseCode= 200, result= {"result_code":"success","data":{"aaa":"111"},"path":"/test/12346/query"}
四、网络拦截器
1、404重试
测试:
String url = "http://localhost:8080/test/12346/query2";
Map<String,String> params = new HashMap<>();
params.put("aaa","111");
params.put("bbb","222");
HttpUtils httpUtils = HttpUtils.getInstance();
httpUtils.post(url,params); 日志打印:
[main][2019-09-21 10:56:20.495] [INFO] [NetworkIntercepter.intercept:38] responseTime= 26, requestUrl= http://localhost:8080/test/12346/query2, params=aaa=111&bbb=222, responseCode= 404, result= {"timestamp":1569034580,"status":404,"error":"Not Found","message":"Not Found","path":"/test/12346/query2"}
[main][2019-09-21 10:56:20.506] [INFO] [NetworkIntercepter.intercept:38] responseTime= 4, requestUrl= http://localhost:8080/test/12346/query2, params=aaa=111&bbb=222, responseCode= 404, result= {"timestamp":1569034580,"status":404,"error":"Not Found","message":"Not Found","path":"/test/12346/query2"}
[main][2019-09-21 10:56:20.512] [INFO] [NetworkIntercepter.intercept:38] responseTime= 4, requestUrl= http://localhost:8080/test/12346/query2, params=aaa=111&bbb=222, responseCode= 404, result= {"timestamp":1569034580,"status":404,"error":"Not Found","message":"Not Found","path":"/test/12346/query2"
重试了2次,共请求3次
2、超时重试
日志打印:
[main][2019-09-21 10:59:30.086] [ERROR] [NetworkIntercepter.intercept:33] timeout
[main][2019-09-21 10:59:30.092] [INFO] [NetworkIntercepter.intercept:38] responseTime= 2009, requestUrl= http://localhost:8080/test/12346/query, params=aaa=111&bbb=222, responseCode= null, result= null
[main][2019-09-21 10:59:32.097] [ERROR] [NetworkIntercepter.intercept:33] timeout
[main][2019-09-21 10:59:32.097] [INFO] [NetworkIntercepter.intercept:38] responseTime= 2004, requestUrl= http://localhost:8080/test/12346/query, params=aaa=111&bbb=222, responseCode= null, result= null
[main][2019-09-21 10:59:34.101] [ERROR] [NetworkIntercepter.intercept:33] timeout
[main][2019-09-21 10:59:34.101] [INFO] [NetworkIntercepter.intercept:38] responseTime= 2002, requestUrl= http://localhost:8080/test/12346/query, params=aaa=111&bbb=222, responseCode= null, result= null
OkHttp3使用教程,实现get、post请求发送,自动重试,打印响应日志。的更多相关文章
- scrapy框架post请求发送,五大核心组件,日志等级,请求传参
一.post请求发送 - 问题:爬虫文件的代码中,我们从来没有手动的对start_urls列表中存储的起始url进行过请求的发送,但是起始url的确是进行了请求的发送,那这是如何实现的呢? - 解答: ...
- 精讲RestTemplate第8篇-请求失败自动重试机制
本文是精讲RestTemplate第8篇,前篇的blog访问地址如下: 精讲RestTemplate第1篇-在Spring或非Spring环境下如何使用 精讲RestTemplate第2篇-多种底层H ...
- 精讲响应式WebClient第6篇-请求失败自动重试机制,强烈建议你看一看
本文是精讲响应式WebClient第6篇,前篇的blog访问地址如下: 精讲响应式webclient第1篇-响应式非阻塞IO与基础用法 精讲响应式WebClient第2篇-GET请求阻塞与非阻塞调用方 ...
- chrome 浏览器的预提取资源机制导致的一个请求发送两次的问题以及ClientAbortException异常
调查一个 pdf 打印报错: ExceptionConverter: org.apache.catalina.connector.ClientAbortException: java.net.Sock ...
- Web爬去的C#请求发送
public class HttpControler { //post请求发送 private Encoding m_Encoding = Encoding.GetEncoding("gb2 ...
- 用Python做大批量请求发送
大批量请求发送需要考虑的几个因素: 1. 服务器承载能力(网络带宽/硬件配置); 2. 客户端IO情况, 客户端带宽, 硬件配置; 方案: 1. 方案都是相对的; 2. 因为这里我的情况是客户机只有一 ...
- ajax请求发送和页面跳转的冲突
http://blog.csdn.net/allenliu6/article/details/77341538?locationNum=7&fps=1 在A页面中,有一个click事件,点击时 ...
- 利用post请求发送内容进行爬虫
利用post请求发送内容进行爬虫 import requests url = 'http://www.iqianyue.com/mypost' header = {} header['Accept-L ...
- 一个http请求发送到后端的详细过程
我们来看当我们在浏览器输入http://www.mycompany.com:8080/mydir/index.html,幕后所发生的一切. 首先http是一个应用层的协议,在这个层的协议,只是一种通讯 ...
随机推荐
- 最小环-Floyd
floyd求最小环 在Floyd的同时,顺便算出最小环. Floyd算法 :k<=n:k++) { :i<k:i++) :j<k:j++) if(d[i][j]+m[i][k]+m[ ...
- 敏捷开发--必备工具Jira&Confluence学习视频
敏捷开发必备工具:Jira+confluence,完美组合. 入门培训视频,内含Jira, Confluence, BigGantt, Zephyr, Tempo, Question, ScriptR ...
- 解决HTML5实现一键拨号、一键发短信及上传头像兼容性问题
HTML5实现一键拨号,一键发短信以及上传头像等问题都是比较常见的场景,近期在做移动端项目的时候遇到阻挠,通过查找资料解决了问题: 废话不多说,直接上案例代码: HTML5实现一键拨号: <a ...
- Hibernate中Criteria的完整用法2
Criteria的完整用法 QBE (Query By Example) Criteria cri = session.createCriteria(Student.class); cri.add(E ...
- PythonI/O进阶学习笔记_2.魔法函数
前言: 本文一切观点和测试代码是在python3的基础上. Content: 1.什么是魔法函数,魔法函数__getitem__在python中应用. 2.python的数据模型和数据模型这种设计对p ...
- 剑指Offer(二十五):复杂链表的复制
剑指Offer(二十五):复杂链表的复制 搜索微信公众号:'AI-ming3526'或者'计算机视觉这件小事' 获取更多算法.机器学习干货 csdn:https://blog.csdn.net/bai ...
- urllib爬虫模块
网络爬虫也称为网络蜘蛛.网络机器人,抓取网络的数据.其实就是用Python程序模仿人点击浏览器并访问网站,而且模仿的越逼真越好.一般爬取数据的目的主要是用来做数据分析,或者公司项目做数据测试,公司业务 ...
- CF #541 E. String Multiplication
题意: 给定一系列字符串,每次都是后一个字符串和前面的融合,这个融合操作就是原来的串分成独立的,然后把新串插入到这些空格中.问最后,最长的相同连续的长度. 思路: 这道题可以贪心的来,我们压缩状态,记 ...
- 求树的重心 DFS
树的重心 何谓重心 树的重心:找到一个点,其所有的子树中最大的子树节点数最少,那么这个点就是这棵树的重心,删去重心后,生成的多棵树尽可能平衡. 树的重心可以通过简单的两次搜索求出,第一遍搜索求出每个结 ...
- Joyful HDU - 5245 概率问题
Sakura has a very magical tool to paint walls. One day, kAc asked Sakura to paint a wall that looks ...