自定義應用攔截器
阿新 • • 發佈:2018-12-21
建立一個類 繼承interceptor
post
public class MyInterceptor implements Interceptor { @Override public Response intercept(Chain chain) throws IOException { //獲取原始的請求資料 Request orginRequest = chain.request(); //先獲取原始的請求引數,然後再拼接起來 FormBody orginBody = (FormBody) orginRequest.body(); FormBody.Builder builder = new FormBody.Builder(); for (int i = 0; i < orginBody.size(); i++) { String name = orginBody.name(i); String value = orginBody.value(i); builder.add(name, value); } FormBody formBody = builder.build(); Request request = new Request.Builder().url(orginRequest.url()).post(formBody).build(); Log.i("TAG","12321"); return chain.proceed(request); } }
get
public class MyInterceptor implements Interceptor{ @Override public Response intercept(Chain chain) throws IOException { Request request = chain.request(); HttpUrl url = request.url(); String string = url.url().toString(); String resultUrl = string+"&source=android"; Request request1 = request.newBuilder().url(resultUrl).build(); return chain.proceed(request); } }
網路請求類
只需要在例項化時新增攔截器即可
private HttpUtils() {
//建立OkHttpClient
//建立攔截器
client = new OkHttpClient.Builder()
.addInterceptor(new MyInterceptor())
.build();
}