Okhttp3添加公共请求头和添加公共请求参数

在利用okhttp进行网络请求时,通常会用到拦截器Interceptor这个东西。但是为请求链接添加拦截器又分为三种添加,第一种:添加请求头,第二种:GET请求添加公共参数,第三种:POST请求添加公共参数。一下就是添加的方法

首先创建一个类实现Interceptor:

public class HttpInterceptorimplements Interceptor{}

然后就是各个添加的方法:
最后在OkhttpClient中添加拦截器:

image

添加请求头方法:

/*//新请求(为什么说新操作是从旧请求里面提取内容信息)
Request.Builder requestBuilder=oldRequest.newBuilder();
requestBuilder.method(oldRequest.method(),oldRequest.body());
//将公共参数添加到请求头header中去
if (mHeaderParamsMap.size()>0){//如果添加了请求头公共参数,Map.size>0
//遍历集合,将参数添加到请求头header中
for (Map.Entry params:mHeaderParamsMap.entrySet()){
requestBuilder.header(params.getKey(),params.getValue());
}
}
//将公共参数添加到请求头后,建立新请求连接
Request newRequest=requestBuilder.build();*/

GET请求添加公共参数方法:

//获取并判断网络请求的方法
        String method = oldRequest.method();
        if (method.equals("GET") && mUrlParamsMap.size() > 0) {//判断,并且判断是否有添加公共参数请求
            //添加公共参数,构建一个新的httpurl请求链接
            HttpUrl modifieUrl = null;//注意:就算下面没有添加公共参数成功,也会执行下去的
            //遍历map集合,将公共参数添加到url中
            modifieUrl=oldRequest.url().newBuilder().build();
            for (Map.Entry params : mUrlParamsMap.entrySet()) {
                modifieUrl = modifieUrl.newBuilder()
                        .addQueryParameter(params.getKey(), params.getValue())
                        .build();

            }
            //初始化新的request请求链接
            newRequest = oldRequest.newBuilder().url(modifieUrl).build();
            //再次发起网络请求,并获得返回的结果
            Response response = chain.proceed(newRequest);
            String content = response.body().string();//拿到返回结果的内容,进行分析
            //获得返回结果的类型
            MediaType contentType = response.body().contentType();
            //生成新的response返回。注意:如果网络请求的response,如果去除后直接返回,将会抛异常
            //注意:response只去一次值,取完后立即清空销毁,所以最好别在这打印日志

            //Log.e("okhttp", "执行拦截添加" + content);

            return response.newBuilder()
                    .body(ResponseBody.create(content, contentType))
                    .build();

        }

POST请求添加公共参数方法:

if (method.equals("POST")) {
            if (oldRequest.body() instanceof FormBody) {
                FormBody.Builder bodyBuilder = new FormBody.Builder();//Charset.forName("UTF-8")
                FormBody formBody = (FormBody) oldRequest.body();
                for (int i = 0; i < formBody.size(); i++) {//---------------注意:一定需要将原来的参数添加到FormBody.Builder里面,等全部参数添加完后,再生成新连接
                    //Log.e("okhttp","formbody里面的参数:"+i+formBody.name(i)+":"+formBody.value(i));
                    bodyBuilder.add(formBody.name(i), formBody.value(i));
                }
                for (Map.Entry params : mUrlParamsMap.entrySet()) {
                    //原本写法
                    //formBody=bodyBuilder.add(params.getKey(),params.getValue()).build();
                    //修改
                    //POST请求方法添加公共参数
                    bodyBuilder.add(params.getKey(), params.getValue());
                    //Log.e("okhttp","公共参数Post"+params.getKey()+":"+params.getValue());
                }

                StringBuffer sb = new StringBuffer();
                formBody = bodyBuilder.build();//修改
                for (int i = 0; i < formBody.size(); i++) {
                    //Log.e("okhttp","body里面的参数:"+i+formBody.name(i)+":"+formBody.value(i));
                    sb.append(formBody.name(i)+"="+formBody.value(i)+"&");
                }
                RequestBody requestBody = RequestBody.create(FORM_CONTENT_TYPE, sb.toString());
                //.addHeader("Content-Type","application/x-www-form-urlencoded; charset=utf-8")
                newRequest = oldRequest.newBuilder().post(requestBody).build();
                Response response = chain.proceed(newRequest);
                String content = response.body().string();

                MediaType contentType = response.body().contentType();
                //Log.e("okhttp","执行拦截添加Post"+content+":"+newRequest.toString());
                printUrl(newRequest, formBody);

                return response.newBuilder()
                        .body(ResponseBody.create(content, contentType))
                        .build();
            }
        }

最后这里把整个代码贴上来:

package com.gn.gdsjjf.baselib.net.interceptor;


import com.gn.gdsjjf.baselib.net.NetConstant;
import com.gn.gdsjjf.baselib.utils.LogUtil;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

import okhttp3.FormBody;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;

public class AddParamsIterceptor implements Interceptor {
    //创建map集合,将添加的公共参数保存到map中
    private Map mUrlParamsMap = new HashMap<>();
    public static final MediaType FORM_CONTENT_TYPE
            = MediaType.parse("application/x-www-form-urlencoded; charset=UTF-8");
    /*//创建map集合,保存添加到请求头的公共参数,添加公共请求头也一样
    private Map mHeaderParamsMap=new HashMap<>();*/

    @NotNull
    @Override
    public Response intercept(@NotNull Chain chain) throws IOException {
        //获得请求连接
        Request oldRequest = chain.request();//旧连接
        Request newRequest;//添加公共参数后的新连接


        /**
         * 这个时添加请求头的
         */
        /*//新请求(为什么说新操作是从旧请求里面提取内容信息)
        Request.Builder requestBuilder=oldRequest.newBuilder();
        requestBuilder.method(oldRequest.method(),oldRequest.body());

        //将公共参数添加到请求头header中去
        if (mHeaderParamsMap.size()>0){//如果添加了请求头公共参数,Map.size>0
            //遍历集合,将参数添加到请求头header中
            for (Map.Entry params:mHeaderParamsMap.entrySet()){
                requestBuilder.header(params.getKey(),params.getValue());
            }
        }
        //将公共参数添加到请求头后,建立新请求连接
        Request newRequest=requestBuilder.build();*/

        //获取并判断网络请求的方法
        String method = oldRequest.method();
        if (method.equals("GET") && mUrlParamsMap.size() > 0) {//判断,并且判断是否有添加公共参数请求
            //添加公共参数,构建一个新的httpurl请求链接
            HttpUrl modifieUrl = null;//注意:就算下面没有添加公共参数成功,也会执行下去的
            //遍历map集合,将公共参数添加到url中
            modifieUrl=oldRequest.url().newBuilder().build();
            for (Map.Entry params : mUrlParamsMap.entrySet()) {
                modifieUrl = modifieUrl.newBuilder()
                        .addQueryParameter(params.getKey(), params.getValue())
                        .build();

            }
            //初始化新的request请求链接
            newRequest = oldRequest.newBuilder().url(modifieUrl).build();
            //再次发起网络请求,并获得返回的结果
            Response response = chain.proceed(newRequest);
            String content = response.body().string();//拿到返回结果的内容,进行分析
            //获得返回结果的类型
            MediaType contentType = response.body().contentType();
            //生成新的response返回。注意:如果网络请求的response,如果去除后直接返回,将会抛异常
            //注意:response只去一次值,取完后立即清空销毁,所以最好别在这打印日志

            //Log.e("okhttp", "执行拦截添加" + content);

            return response.newBuilder()
                    .body(ResponseBody.create(content, contentType))
                    .build();

        } else if (method.equals("POST")) {
            if (oldRequest.body() instanceof FormBody) {
                FormBody.Builder bodyBuilder = new FormBody.Builder();//Charset.forName("UTF-8")
                FormBody formBody = (FormBody) oldRequest.body();
                for (int i = 0; i < formBody.size(); i++) {//---------------注意:一定需要将原来的参数添加到FormBody.Builder里面,等全部参数添加完后,再生成新连接
                    //Log.e("okhttp","formbody里面的参数:"+i+formBody.name(i)+":"+formBody.value(i));
                    bodyBuilder.add(formBody.name(i), formBody.value(i));
                }
                for (Map.Entry params : mUrlParamsMap.entrySet()) {
                    //原本写法
                    //formBody=bodyBuilder.add(params.getKey(),params.getValue()).build();
                    //修改
                    //POST请求方法添加公共参数
                    bodyBuilder.add(params.getKey(), params.getValue());
                    //Log.e("okhttp","公共参数Post"+params.getKey()+":"+params.getValue());
                }

                StringBuffer sb = new StringBuffer();
                formBody = bodyBuilder.build();//修改
                for (int i = 0; i < formBody.size(); i++) {
                    //Log.e("okhttp","body里面的参数:"+i+formBody.name(i)+":"+formBody.value(i));
                    sb.append(formBody.name(i)+"="+formBody.value(i)+"&");
                }
                RequestBody requestBody = RequestBody.create(FORM_CONTENT_TYPE, sb.toString());
                //.addHeader("Content-Type","application/x-www-form-urlencoded; charset=utf-8")
                newRequest = oldRequest.newBuilder().post(requestBody).build();
                Response response = chain.proceed(newRequest);
                String content = response.body().string();

                MediaType contentType = response.body().contentType();
                //Log.e("okhttp","执行拦截添加Post"+content+":"+newRequest.toString());
                printUrl(newRequest, formBody);

                return response.newBuilder()
                        .body(ResponseBody.create(content, contentType))
                        .build();
            }
        }
        return chain.proceed(oldRequest);
    }

    /**
     * 打印请求链接
     *
     * @param newRequest
     * @param formBody
     */
    private void printUrl(Request newRequest, FormBody formBody) {
        StringBuilder sb = new StringBuilder(newRequest.url() + "");
        for (int i = 0; i < formBody.size(); i++) {
            sb.append(formBody.encodedName(i) + "=" + formBody.encodedValue(i) + "&");
        }
        sb.deleteCharAt(sb.length() - 1);
        if (NetConstant.debug) {
            LogUtil.e("请求链接", sb.toString());
        }
    }

    /**
     * 创建一个静态类,用于添加公共参数到map集合缓存
     */
    public static class Builder {
        //创建拦截器对象,得到Map存储添加进来的公共参数
        AddParamsIterceptor addParamsIterceptor;

        public Builder() {//构造方法中初始话拦截器
            addParamsIterceptor = new AddParamsIterceptor();
        }

        /**
         * 将公共参数添加到map集合
         *
         * @param key
         * @param value
         * @return
         */
        public Builder addUrlParams(String key, String value) {
            addParamsIterceptor.mUrlParamsMap.put(key, value);
            return this;
        }

        public Builder addUrlParams(String key, double value) {
            return addUrlParams(key, String.valueOf(value));
        }

        public Builder addUrlParams(String key, int value) {
            return addUrlParams(key, String.valueOf(value));
        }

        public Builder addUrlParams(String key, long value) {
            return addUrlParams(key, String.valueOf(value));
        }

        public Builder addUrlParams(String key, float value) {
            return addUrlParams(key, String.valueOf(value));
        }

        /**
         * 返回建立拦截器
         *
         * @return
         */
        public AddParamsIterceptor build() {
            return addParamsIterceptor;
        }

    }
}

小小的尝试,希望对各位有用,如果又哪里需要改正的地方,请多多指教!谢谢

参考链接:https://blog.csdn.net/qq_38450133/article/details/81218114

你可能感兴趣的:(Okhttp3添加公共请求头和添加公共请求参数)