在看到這篇文章時卿拴,希望你已經(jīng)閱讀過OkHttp對Interceptor的正式介紹衫仑,地址在這里,同時堕花,你還可以知道okhttp-logging-interceptor這個輔助庫文狱,當然如果你沒有閱讀過也并無大礙,這篇文章重在描述使用場景和個人心得缘挽;
在去年網(wǎng)上討論最多的就是OkHttp和Volley的比較瞄崇,我當時決定把項目中的Volley換成OkHttp2,是因為在弱網(wǎng)環(huán)境下測試壕曼,OkHttp比較堅強杠袱,所以就用它了,并不是對Square的情懷窝稿;在一年多的使用中,不論是從2.x版本升到3.x凿掂,OkHttp絕對是最好用的庫伴榔,特別是加之Retrofit纹蝴,如虎添翼;
這篇文章是講Interceptor的使用心得踪少,這就根據(jù)我所用塘安,總結出這么幾點:
- Log輸出
- 增加公共請求參數(shù)
- 修改請求頭
- 加密請求參數(shù)
- 服務器端錯誤碼處理(時間戳異常為例)
這幾點絕不是全面,但至少是目前很多開發(fā)者或多或少都會遇到的問題援奢,Log輸出是必須有的兼犯,公共參數(shù)這是必須有的,請求頭加密和參數(shù)加密集漾,這個不一定都有切黔;重點是服務端錯誤碼處理,這個放在哪里處理具篇,見仁見智纬霞,但是有些比較惡心的錯誤,比如時間戳異常(請求任何一個服務器接口時必須攜帶時間戳參數(shù)驱显,服務器專門有提供時間戳的接口诗芜,這個時間戳要和服務器時間戳同步,容錯在5秒埃疫,否則就返回時間戳錯誤)伏恐,比如客戶端修改系統(tǒng)時間時這一刻又斷網(wǎng)了,監(jiān)聽時間變化也沒用栓霜,又不可能定時去獲取翠桦,所以何時需要同步,去請求這個接口成了問題叙淌,我處理的方案是在Interceptor中過濾結果秤掌,當某個接口返回時間戳異常時,不把結果往上返鹰霍,再執(zhí)行一次時間戳接口闻鉴,如果獲取成功,傳入?yún)?shù)并重構之前的請求茂洒,如果獲取失敗孟岛,把之前時間戳異常的接果返回。
說了這幾條督勺,其實具體實現(xiàn)要回歸到Interceptor這個類
我們要實現(xiàn):
- 解析出來請求參數(shù)
- 對請求進行重構
- 解析出Response結果
- 重構Response
首先渠羞,Log輸出可以直接使用官方的https://github.com/square/okhttp/tree/master/okhttp-logging-interceptor,
這只有一個類智哀,我這篇文章解析Response的核心代碼其實是參考了這個庫次询;
我們自己來做,第一步瓷叫,就要實現(xiàn)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;}
如何解析出請求參數(shù)
/**
* 解析請求參數(shù)
* @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方式的請求參數(shù)
* @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;
}
/**
* 獲取表單的請求參數(shù)
* @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;
}
}
解析參數(shù)就是判斷請求類型送巡,get類型是從url解析參數(shù),其他類型是從FormBody取盒卸,可以上傳文件的表單請求暫時沒有考慮進來骗爆;
重構Request增加公共參數(shù)
@Override
public Request handlerRequest(Request request) {
Map<String, String> params = parseParams(Request);
if (params == null) {
params = new HashMap<>();
}
//這里為公共的參數(shù)
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;
}
}
解析Response過程是對Reponse對象的操作专钉,這里用的是Okio中的Source進行讀取,參考的okhttp-logging-interceptor代碼中的寫法累铅,在獲取Reponse對象是跃须,切不可直接操作response.body().bytes()或者 response.body().string(),數(shù)據(jù)只能讀取一次娃兽,等著真正調用的時候菇民, response.body().string()返回為null,這個問題描述在這里
解決時間戳的問題投储,其實就是解析出結果中的錯誤碼==300時(300是和服務器約定)第练,構造出請求時間戳的Request,拿當前的Chain執(zhí)行它就可以了玛荞,返回正確的時間戳之后娇掏,就可以拿正確的參數(shù)重構Request,然后Chain執(zhí)行就Ok了勋眯。
結束語:這些都是我自己使用的體會婴梧,沒用Interceptor之前,我是把公共參數(shù)和加密放在網(wǎng)絡請求之前處理客蹋,時間戳的處理塞蹭,目前是用RxJava的map操作來處理,但是我覺得用Interceptor實現(xiàn)是最簡潔的讶坯,準備下一步把它挪到Interceptor里番电,目前已知的缺點就是和OkHttp依賴太深,如果你的項目中已經(jīng)集成OkHttp辆琅,機智的你可以動手試一試漱办。