因为项目中有一个需求,就是SessionId是否过期,如果过期就需要用户重新登录。有限期是半个小时,超过半个小时,后台哥们就会返回403。所以我需要做的就是拦截网络请求。提前获取Response,并对网络状态码进行判断。如果403,就调登录接口,获取最新SessionId,然后重新发起请求。
代码有点乱,大家凑合看0.0
下面是我定义的网络拦截器
private GlobalHttpHandler mHandler;
public RequestIntercept(GlobalHttpHandler mHandler) {
this.mHandler = mHandler;
}
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
Buffer requestbuffer = new Buffer();
if (request.body() != null) {
request.body().writeTo(requestbuffer);
} else {
Timber.tag("Request").w("request.body() == null");
}
if (mHandler != null)//在请求服务器之前可以拿到request,做一些操作比如给request添加header,如果不做操作则返回参数中的request
request = mHandler.onHttpRequestBefore(chain, request);
//打印url信息
Timber.tag("Request")
.w("Sending Request %s on %n Params ---> %s%n Connection ---> %s%n Headers ---> %s", request.url(), request.body() != null ? requestbuffer.readUtf8() : "null", chain
.connection(), request.headers());
long t1 = System.nanoTime();
Response originalResponse = chain.proceed(request);
long t2 = System.nanoTime();
//打赢响应时间
Timber.tag("Response").w("Received response in %.1fms%n%s", (t2 - t1) / 1e6d, originalResponse.headers());
//读取服务器返回的结果
ResponseBody responseBody = originalResponse.body();
BufferedSource source = responseBody.source();
source.request(Long.MAX_VALUE); // Buffer the entire body.
Buffer buffer = source.buffer();
//获取content的压缩类型
String encoding = originalResponse.headers().get("Content-Encoding");
Buffer clone = buffer.clone();
String bodyString;
//解析response content
if (encoding != null && encoding.equalsIgnoreCase("gzip")) {//content使用gzip压缩
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
clone.writeTo(outputStream);
byte[] bytes = outputStream.toByteArray();
bodyString = ZipHelper.decompressForGzip(bytes);//解压
outputStream.close();
} else if (encoding != null && encoding.equalsIgnoreCase("zlib")) {//content使用zlib压缩
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
clone.writeTo(outputStream);
byte[] bytes = outputStream.toByteArray();
bodyString = ZipHelper.decompressToStringForZlib(bytes);//解压
outputStream.close();
} else {//content没有被压缩
Charset charset = Charset.forName("UTF-8");
MediaType contentType = responseBody.contentType();
if (contentType != null) {
charset = contentType.charset(charset);
}
bodyString = clone.readString(charset);
}
Timber.tag("Result").w(jsonFormat(bodyString));
if (mHandler != null)//这里可以比客户端提前一步拿到服务器返回的结果,可以做一些操作,比如token超时,重新获取
return mHandler.onHttpResultResponse(bodyString, chain, originalResponse);
return originalResponse;
}
GlobalHttpHandler 是我定义的一个接口,用于回调。
下面是实现
return new GlobalHttpHandler() {
@Override
public Response onHttpResultResponse(String httpResult, Interceptor.Chain chain, Response response) {
Request request = chain.request();
HttpUrl url = request.url();
if (response.code() == 403) {
if (!TextUtils.isEmpty(UserController.getInstance().getUserId())&&!TextUtils.isEmpty(UserController.getInstance().getPassword()))
{
//这里使用同步请求,直接拿到结果
Call<BaseBean<LoginBean>> call = LoginUtil.autoLogin();
response.body().close();
//设置新的Cookie
Request cookie = chain.request().newBuilder().header("Cookie", Cookie).build();
try {
//重新请求
return chain.proceed(cookie);
} catch (IOException e) {
e.printStackTrace();
}
}
} else {
return response;
}
return response;
}
@Override
public Request onHttpRequestBefore(Interceptor.Chain chain, Request request) {
//获取请求request
Request build = null;
try {
build = request.newBuilder()
.addHeader("Content-Type", "application/json;charset=utf-8")
.addHeader("Cookie", Cookie)
.url(URLDecoder.decode(request.url().url().toString(), "utf-8"))
.build();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return build;
}
};
}
OK,齐活。
...
...
...
但是在调的时候虽然可以重新登录,但是却收不到之前的请求。
一看发现原来报错了
network interceptor must call proceed() exactly once
网络拦截器只能调用一次proceed()。
然后在去看我添加拦截器的代码
OkHttpClient.Builder builder = okHttpClient.connectTimeout(TOME_OUT, TimeUnit.SECONDS)
.readTimeout(TOME_OUT, TimeUnit.SECONDS).cache(cache)//设置缓存
.addNetworkInterceptor(intercept);
if (mInterceptors != null && mInterceptors.length > 0) {//如果外部提供了interceptor的数组则遍历添加
for (Interceptor interceptor : mInterceptors) {
builder.addInterceptor(interceptor);
}
}
return builder.build();
}
发现添加的是网络拦截器。
然后我换成addInterceptor() ,发现没问题了。
这两个方法到底有什么区别呢,去查看官网发现了介绍
https://github.com/square/okhttp/wiki/Interceptors
官网给的关于Interceptors的说明非常详细。推荐大家阅读。
下面简单说一下区别
addInterceptor()方法表示添加的是Application Interceptor
而addNetworkInterceptor()方法表示添加的是 NetworkInterceptor
Application interceptors 的特点
Don't need to worry about intermediate responses like redirects and retries.
Are always invoked once, even if the HTTP response is served from the cache.
Observe the application's original intent. Unconcerned with OkHttp-injected headers like If-None-Match.
Permitted to short-circuit and not call Chain.proceed().
Permitted to retry and make multiple calls to Chain.proceed().
1.不需要担心中间重试或者重定向返回的响应
2.总是会被调用一次,即使响应结果是从缓存中取的
3.只关注最原始的应用请求,不关心注入的请求头,比如(If-None-Match)
4.允许不调用Chain.proceed()的短期循环
5.允许重试并且多次调用Chain.proceed()
Network Interceptors的特点
Able to operate on intermediate responses like redirects and retries.
Not invoked for cached responses that short-circuit the network.
Observe the data just as it will be transmitted over the network.
Access to the Connection that carries the request.
1.可以对重连或者重定向所返回的中间的响应结果进行操作
2.网络中断不会调起缓存响应
3.可以获取到通过网络透传的数据
4.可以访问带着请求的连接
渣渣翻译,请大佬指正0.0
其中有一条
Permitted to retry and make multiple calls to Chain.proceed().
允许重试或多次调用Chain.proceed()方法
但是Network Interceptors就不支持了。
OK,记录一下遇到的错误,希望可以帮到其他同学。