美文网首页
Okhttp请求拦截器

Okhttp请求拦截器

作者: 豌豆与毛豆 | 来源:发表于2017-02-22 16:05 被阅读0次

Okhttp请求拦截器

1.新建拦截器,实现Interceptor接口

public class MyInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
      
    }
}

2.获取Request对象

Request original = chain.request();

3.获取、修改HttpUrl对象

HttpUrl url = original.url();

//获得url中key值为name的参数值
String name = url.queryParameter("name");
//添加参数
HttpUrl newUrl = url.newBuilder()
        .addQueryParameter("key","value")
        .build();

4.获取、修改Body对象

//获取、添加body参数
if (original.body() instanceof FormBody){
    FormBody oldBody = (FormBody) original.body();
    FormBody.Builder bodyBuilder = new FormBody.Builder();
    //添加参数
    bodyBuilder.add("key","value");
    for (int i = 0; i < oldBody.size(); i ++){
        String key = oldBody.encodedName(i);
        String value = oldBody.encodedValue(i);
    }
}

5.添加请求头

//获取、修改请求头
Headers headers = original.headers();
Headers newHeader = headers.newBuilder()
        .add("X-Access-Token", MyApplication.getInstance().getToken())
        .build();
Request.Builder builder = original.newBuilder()
                .headers(newHeader);

6.修改Request对象

Request.Builder builder = original.newBuilder()
                .headers(newHeader);
Request request = builder.build();
Response response = chain.proceed(request);

完整拦截器代码

public class MyInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request original = chain.request();

        HttpUrl url = original.url();

        //获得url中key为name的参数值
        String name = url.queryParameter("key");

        //添加参数
        HttpUrl newUrl = url.newBuilder()
                .addQueryParameter("key","value")
                .build();

        //获取、添加body参数
        if (original.body() instanceof FormBody){
            FormBody oldBody = (FormBody) original.body();
            FormBody.Builder bodyBuilder = new FormBody.Builder();
            //添加参数
            bodyBuilder.add("key","value");

            for (int i = 0; i < oldBody.size(); i ++){
                String key = oldBody.encodedName(i);
                String value = oldBody.encodedValue(i);
            }
        }

        //获取、修改请求头
        Headers headers = original.headers();
        Headers newHeader = headers.newBuilder()
                .add("X-Access-Token", MyApplication.getInstance().getToken())
                .build();


        Request.Builder builder = original.newBuilder()
                .headers(newHeader);

        Request request = builder.build();

        Response response = chain.proceed(request);

        return response;
    }
}

相关文章

网友评论

      本文标题:Okhttp请求拦截器

      本文链接:https://www.haomeiwen.com/subject/isjmwttx.html