一、创建线程安全的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请求发送,自动重试,打印响应日志。的更多相关文章

  1. scrapy框架post请求发送,五大核心组件,日志等级,请求传参

    一.post请求发送 - 问题:爬虫文件的代码中,我们从来没有手动的对start_urls列表中存储的起始url进行过请求的发送,但是起始url的确是进行了请求的发送,那这是如何实现的呢? - 解答: ...

  2. 精讲RestTemplate第8篇-请求失败自动重试机制

    本文是精讲RestTemplate第8篇,前篇的blog访问地址如下: 精讲RestTemplate第1篇-在Spring或非Spring环境下如何使用 精讲RestTemplate第2篇-多种底层H ...

  3. 精讲响应式WebClient第6篇-请求失败自动重试机制,强烈建议你看一看

    本文是精讲响应式WebClient第6篇,前篇的blog访问地址如下: 精讲响应式webclient第1篇-响应式非阻塞IO与基础用法 精讲响应式WebClient第2篇-GET请求阻塞与非阻塞调用方 ...

  4. chrome 浏览器的预提取资源机制导致的一个请求发送两次的问题以及ClientAbortException异常

    调查一个 pdf 打印报错: ExceptionConverter: org.apache.catalina.connector.ClientAbortException: java.net.Sock ...

  5. Web爬去的C#请求发送

    public class HttpControler { //post请求发送 private Encoding m_Encoding = Encoding.GetEncoding("gb2 ...

  6. 用Python做大批量请求发送

    大批量请求发送需要考虑的几个因素: 1. 服务器承载能力(网络带宽/硬件配置); 2. 客户端IO情况, 客户端带宽, 硬件配置; 方案: 1. 方案都是相对的; 2. 因为这里我的情况是客户机只有一 ...

  7. ajax请求发送和页面跳转的冲突

    http://blog.csdn.net/allenliu6/article/details/77341538?locationNum=7&fps=1 在A页面中,有一个click事件,点击时 ...

  8. 利用post请求发送内容进行爬虫

    利用post请求发送内容进行爬虫 import requests url = 'http://www.iqianyue.com/mypost' header = {} header['Accept-L ...

  9. 一个http请求发送到后端的详细过程

    我们来看当我们在浏览器输入http://www.mycompany.com:8080/mydir/index.html,幕后所发生的一切. 首先http是一个应用层的协议,在这个层的协议,只是一种通讯 ...

随机推荐

  1. scrapy xpath用法

    一.实验环境 1.Windows7x64_SP1 2.anaconda3 + python3.7.3(anaconda集成,不需单独安装) 3.scrapy1.6.0 二.用法举例 1.开启scrap ...

  2. python实现RSA加密和签名以及分段加解密的方案

    1.前言 很多朋友在工作中,会遇到一些接口使用RSA加密和签名来处理的请求参数,那么遇到这个问题的时候,第一时间当然是找开发要加解密的方法,但是开发给加解密代码,大多数情况都是java,c++,js等 ...

  3. yolo v2

    https://blog.csdn.net/wfei101/article/details/79398563 https://blog.csdn.net/oppo62258801/article/de ...

  4. 实战SpringCloud响应式微服务系列教程(第四章)

    接上一篇: 实战SpringCloud响应式微服务系列教程(第一章) 实战SpringCloud响应式微服务系列教程(第二章) 实战SpringCloud响应式微服务系列教程(第三章) 1.1.4 引 ...

  5. 设置ABP默认使用中文

    ABP提供的启动模板, 默认使用是英文: 虽然可以通过右上角的菜单切换成中文, 但是对于国内项目来说, 默认使用中文是很正常的需求. 本文介绍了如何实现默认语言的几种方法, 希望能对ABP爱好者有所帮 ...

  6. Java基础之访问权限控制

    Java基础之访问权限控制 四种访问权限 Java中类与成员的访问权限共有四种,其中三种有访问权限修饰词:public,protected,private. Public:权限最大,允许所有类访问,但 ...

  7. Java 安全之:csrf防护实战分析

    上文总结了csrf攻击以及一些常用的防护方式,csrf全称Cross-site request forgery(跨站请求伪造),是一类利用信任用户已经获取的注册凭证,绕过后台用户验证,向被攻击网站发送 ...

  8. 迁移桌面程序到MS Store(10)——在Windows S Mode运行

    首先简单介绍Windows 10 S Mode,Windows在该模式下,只能跑MS Store里的软件,不能通过其他方式安装.好处是安全有保障,杜绝一切国产流氓软件.就像iOS一样,APP进商店都需 ...

  9. Java连载25-方法讲解

    一.方法 1.方法的基础语法 (1)例子 //需求1:请编写程序计算10和20的和,并将结果输出 int a = 10; int b = 20; System.out.print(a + " ...

  10. CF #535 (Div. 3) E2 Array and Segments (Hard version) 利用线段树进行区间转移

    传送门 题意:    有m个区间,n个a[ i ] , 选择若干个区间,使得整个数组中的最大值和最小值的差值最小.n<=1e5,m<=300; 思路: 可以知道每个i,如果一个区间包含这个 ...