OkHttp3中Interceptor使用场景
在看到这篇文章时,希望你已经阅读过OkHttp对Interceptor的正式介绍,地址在这里,同时,你还可以知道okhttp-logging-interceptor这个辅助库,当然如果你没有阅读过也并无大碍,这篇文章重在描述使用场景和个人心得;
这篇文章主要从以下几点讲述Interceptor的使用场景
- Log输出
- 增加公共请求参数
- 修改请求头
- 加密请求参数
- 服务器端错误码处理(时间戳异常为例)
这几点绝不是全面,但至少是目前很多开发者或多或少都会遇到的问题,Log输出是必须有的,公共参数这是必须有的,请求头加密和参数加密,这个不一定都有;重点是服务端错误码处理,这个放在哪里处理,见仁见智,但是有些比较恶心的错误,比如时间戳异常(请求任何一个服务器接口时必须携带时间戳参数,服务器专门有提供时间戳的接口,这个时间戳要和服务器时间戳同步,容错在5秒,否则就返回时间戳错误),比如客户端修改系统时间时这一刻又断网了,监听时间变化也没用,又不可能定时去获取,所以何时需要同步,去请求这个接口成了问题,我处理的方案是在Interceptor中过滤结果,当某个接口返回时间戳异常时,不把结果往上返,再执行一次时间戳接口,如果获取成功,传入参数并重构之前的请求,如果获取失败,把之前时间戳异常的接果返回。
说了这几条,其实具体实现要回归到Interceptor这个类
我们要实现:
- 解析出来请求参数
- 对请求进行重构
- 解析出Response结果
- 重构Response
首先,Log输出可以直接使用官方的https://github.com/square/okhttp/tree/master/okhttp-logging-interceptor,这只有一个类,我这篇文章解析Response的核心代码其实是参考了这个库;
我们自己来做,第一步,就要实现Interceptor接口,重写Response intercept(Chain chain)方法
@Overridepublic Response intercept(Chain chain) throws IOException {
Request request = chain.request();
request = handlerRequest(request);
if (request == null) {
throw new RuntimeException("Request返回值不能为空");
}
Response response = handlerRespose(chain.proceed(request), chain);
if (response==null){
throw new RuntimeException("Response返回值不能为空");
}
return response;
}
如何解析出请求参数
/**
* 解析请求参数
* @param request
* @return
*/
public static Map<String, String> parseParams(Request request) {
//GET POST DELETE PUT PATCH
String method = request.method();
Map<String, String> params = null;
if ("GET".equals(method)) {
params = doGet(request);
} else if ("POST".equals(method) || "PUT".equals(method) || "DELETE".equals(method) || "PATCH".equals(method)) {
RequestBody body = request.body();
if (body != null && body instanceof FormBody) {
params = doForm(request);
}
}
return params;
}
/**
* 获取get方式的请求参数
* @param request
* @return
*/
private static Map<String, String> doGet(Request request) {
Map<String, String> params = null;
HttpUrl url = request.url();
Set<String> strings = url.queryParameterNames();
if (strings != null) {
Iterator<String> iterator = strings.iterator();
params = new HashMap<>();
int i = 0;
while (iterator.hasNext()) {
String name = iterator.next();
String value = url.queryParameterValue(i);
params.put(name, value);
i++;
}
}
return params;
}
/**
* 获取表单的请求参数
* @param request
* @return
*/
private static Map<String, String> doForm(Request request) {
Map<String, String> params = null;
FormBody body = null;
try {
body = (FormBody) request.body();
} catch (ClassCastException c) {
}
if (body != null) {
int size = body.size();
if (size > 0) {
params = new HashMap<>();
for (int i = 0; i < size; i++) {
params.put(body.name(i), body.value(i));
}
}
}
return params;
}
}
解析参数就是判断请求类型,get类型是从url解析参数,其他类型是从FormBody取,可以上传文件的表单请求暂时没有考虑进来;
重构Request增加公共参数
@Override
public Request handlerRequest(Request request) {
Map<String, String> params = parseParams(Request);
if (params == null) {
params = new HashMap<>();
}
//这里为公共的参数
params.put("common", "value");
params.put("timeToken", String.valueOf(TimeToken.TIME_TOKEN));
String method = request.method();
if ("GET".equals(method)) {
StringBuilder sb = new StringBuilder(customRequest.noQueryUrl);
sb.append("?").append(UrlUtil.map2QueryStr(params));
return request.newBuilder().url(sb.toString()).build();
} else if ("POST".equals(method) || "PUT".equals(method) || "DELETE".equals(method) || "PATCH".equals(method)) {
if (request.body() instanceof FormBody) {
FormBody.Builder bodyBuilder = new FormBody.Builder();
Iterator<Map.Entry<String, String>> entryIterator = params.entrySet().iterator();
while (entryIterator.hasNext()) {
String key = entryIterator.next().getKey();
String value = entryIterator.next().getValue();
bodyBuilder.add(key, value);
}
return request.newBuilder().method(method, bodyBuilder.build()).build();
}
}
return request;
}
关于重构Request就是调用request.newBuilder()方法,该方法会把当前Request对象所以属性住一个copy,构建出新的Builder对象
重写请求头 (拿的官方示例来做讲解)
/** This interceptor compresses the HTTP request body. Many webservers can't handle this! */
final class GzipRequestInterceptor implements Interceptor {
@Override public Response intercept(Interceptor.Chain chain) throws IOException {
Request originalRequest = chain.request();
//如果请求头不为空,直接proceed
if (originalRequest.body() == null || originalRequest.header("Content-Encoding") != null) {
return chain.proceed(originalRequest);
}
//否则,重构request
Request compressedRequest = originalRequest.newBuilder()
.header("Content-Encoding", "gzip")
.method(originalRequest.method(), gzip(originalRequest.body()))
.build();
return chain.proceed(compressedRequest);
}
private RequestBody gzip(final RequestBody body) {
return new RequestBody() {
@Override public MediaType contentType() {
return body.contentType();
}
@Override public long contentLength() {
return -1; // We don't know the compressed length in advance!
}
@Override public void writeTo(BufferedSink sink) throws IOException {
BufferedSink gzipSink = Okio.buffer(new GzipSink(sink));
body.writeTo(gzipSink);
gzipSink.close();
}
};
}
}
上面示例是对原始的request内容进行处理,貌似是对请求体进行gzip处理,这个一般是在响应头中的声明,请求头一般声明"Accept-Encoding"。
对Response进行解析
@Override
public Response handlerResponse(DFBRestInterceptor.CustomResponse customResponse) {
// 钥匙链对象chain
Interceptor.Chain chain = customResponse.chain;
//真正的Response对象
Response response = customResponse.response;
//该请求的request对象
Request request = chain.request();
//获取Response结果
String string = readResponseStr(response);
JSONObject jsonObject;
try {
jsonObject = new JSONObject(string);
//这个code就是服务器返回的错误码,假设300是时间戳异常
int code = jsonObject.optInt("code");
if (code == 300) {
//构造时间戳Request
Request time = new Request.Builder().url("http://192.168.1.125:8080/getServerTime").build();
//请求时间戳接口
Response timeResponse = chain.proceed(time);
//解析时间戳结果
String timeResStr = readResponseStr(timeResponse);
JSONObject timeObject = new JSONObject(timeResStr);
long date = timeObject.optLong("date");
TimeToken.TIME_TOKEN = date;
时间戳赋值,
if (date > 0) {
//重构Request请求
request = handlerRequest(CustomRequest.create(request));
//拿新的结果进行返回
response = chain.proceed(request);
}
}
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
/**
* 读取Response返回String内容
* @param response
* @return
*/
private String readResponseStr(Response response) {
ResponseBody body = response.body();
BufferedSource source = body.source();
try {
source.request(Long.MAX_VALUE);
} catch (Exception e) {
e.printStackTrace();
return null;
}
MediaType contentType = body.contentType();
Charset charset = Charset.forName("UTF-8");
if (contentType != null) {
charset = contentType.charset(charset);
}
String s = null;
Buffer buffer = source.buffer();
if (isPlaintext(buffer)) {
s = buffer.clone().readString(charset);
}
return s;
}
static boolean isPlaintext(Buffer buffer) {
try {
Buffer prefix = new Buffer();
long byteCount = buffer.size() < 64 ? buffer.size() : 64;
buffer.copyTo(prefix, 0, byteCount);
for (int i = 0; i < 16; i++) {
if (prefix.exhausted()) {
break;
}
int codePoint = prefix.readUtf8CodePoint();
if (Character.isISOControl(codePoint) && !Character.isWhitespace(codePoint)) {
return false;
}
}
return true;
} catch (EOFException e) {
return false; // Truncated UTF-8 sequence.
}
}
/**
* 自定义Response对象,装载Chain和Response
*/
public static class CustomResponse {
public Response response;
public Chain chain;
public CustomResponse(Response response, Chain chain) {
this.response = response;
this.chain = chain;
}
}