我们在创建OkHttp客户端时,可以添加各种拦截器,这是我见过最有可玩性的库之一:
| 12
 3
 4
 5
 6
 
 | OkHttpClient okHttpClient = new OkHttpClient.Builder().connectTimeout(10, TimeUnit.SECONDS)
 .addInterceptor(new XXXInterceptor())
 .addInterceptor(new YYYInterceptor())
 ....
 .build();
 
 | 
设想这么一个场景,用户有一个开关,可以允许或禁止应用内的一切网络请求,如何用拦截器来实现?
为了不让大家觉得我又在水贴,直入主题。
我们可以通过构造一个404的response来拦截请求:
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 
 | private static class NetworkInterceptor implements Interceptor {@Override
 public okhttp3.Response intercept(Chain chain) throws IOException {
 if () {
 return new okhttp3.Response.Builder()
 .code(404)
 .protocol(Protocol.HTTP_2)
 .message("Network is closed by mom")
 .body(ResponseBody.create(MediaType.get("text/html; charset=utf-8"), ""))
 .request(chain.request())
 .build();
 } else {
 return chain.proceed(chain.request());
 }
 }
 }
 
 | 
一定要记住哦,code,protocol,message,body缺一不可。