android 拦截器

public class MyApp extends Application{
    private static OkHttpClient okHttpClient;

    @Override
    public void onCreate() {
        super.onCreate();
        ImageLoaderConfiguration imageLoaderConfiguration=new ImageLoaderConfiguration.Builder(this).build();
        ImageLoader.getInstance().init(imageLoaderConfiguration);
        okHttpClient = new OkHttpClient.Builder()
                .readTimeout(15, TimeUnit.SECONDS)
                .writeTimeout(15, TimeUnit.SECONDS)
                .connectTimeout(15, TimeUnit.SECONDS)
                .addInterceptor(new MyInterceptor())
                .build();
    }
    public static OkHttpClient getOkHttpClient(){
        return okHttpClient;
    }
    class MyInterceptor implements Interceptor {

        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            if("POST".equalsIgnoreCase(request.method())){
                //拿到旧的formbody
                RequestBody oldbody = request.body();
                if(oldbody instanceof FormBody){
                    //构造一个新的FormBody
                    FormBody.Builder builder=new FormBody.Builder();
                    //新的FormBody去添加参数
                     builder.add("source","android");
                    FormBody old= (FormBody) oldbody;
                    for (int i=0;i;i++){
                        builder.add(old.encodedName(i),old.encodedValue(i));
                    }
                    FormBody newbody=builder.build();
                    request=request.newBuilder()
                            .url(request.url())
                            .post(newbody)
                            .build();
                }
            }
            Response response=chain.proceed(request);
            return response;
        }
    }
}

你可能感兴趣的:(android 拦截器)