1. 程式人生 > >網路攔截器

網路攔截器

建一個 PublicParamInterceptor類

public class PublicParamInterceptor implements Interceptor{
Map<String,String> paramMap;

public PublicParamInterceptor(Map<String, String> paramMap) {
    this.paramMap = paramMap;
}

@Override
public Response intercept(Chain chain) throws IOException {

    //拿到原來的request
    Request oldrequest = chain.request();
    //拿到請求的url
    String url = oldrequest.url().toString();
    //判斷是GET還是POST請求
    if (oldrequest.method().equalsIgnoreCase("GET")){
        if(paramMap !=null && paramMap.size() >0){
            StringBuilder urlBuilder = new StringBuilder(url);

            //拼接公共請求引數
            for (Map.Entry<String,String> entry : paramMap.entrySet()){
                urlBuilder.append("&" +entry.getKey() +"=" +entry.getValue());
            }
            url = urlBuilder.toString();
            //如果之前的url沒有?號,手動新增一個
            if (url.contains("?")){
                url = url.replaceFirst("&","?");
            }
            //依據原來的request構造一個新的
            Request request = oldrequest.newBuilder().url(url).build();
            return chain.proceed(request);
        }
    }else {//如果是POST請求
        if (paramMap !=null && paramMap.size() >0){
            RequestBody body = oldrequest.body();
            if (body!=null && body instanceof FormBody){
                FormBody formBody = (FormBody) body;
                FormBody.Builder builder = new FormBody.Builder();
                //為了防止重複新增相同的key和value
                Map<String,String> temMap = new HashMap<>();
                for (int i = 0; i < formBody.size(); i++) {
                    builder.add(formBody.encodedName(i),formBody.encodedValue(i));
                    temMap.put(formBody.encodedName(i),formBody.encodedValue(i));
                }
                //公共請求引數新增到新的body中
                for (Map.Entry<String,String> entry:paramMap.entrySet()){
                    if (!temMap.containsKey(entry.getKey())){
                        builder.add(entry.getKey(),entry.getValue());
                    }
                }
                FormBody newFormBody = builder.build();
                //依據原來的request構造一個新的request
                Request request = oldrequest.newBuilder()
                        .post(newFormBody)
                        .build();
                return chain.proceed(request);
            }
        }
    }

    return chain.proceed(oldrequest);
}

}

在okhttputils中呼叫

在這裡插入圖片描述