Okhttp的Post请求参数在Interceptor中修改

注意

基于老板本的okhttp和rxJava,本博客可能不适配新版的okhttp和rxJava、retrofit

android在使用rxjava+retrofit+okhttp时有时需要对请求参数进行再次处理。
如下规则:
所有的接口,默认需要带上sign,timestamp2个参数。
sign: 参数名+参数值拼接之后,先做base64编码,再做md5加密(加入timestamp, 不加入sign)
参数名 的排序规则按照 ascii 码顺序进行排序
timestamp: (时间戳,秒级)
备注: 参数名和参数值 按照 参数名的ascii 排序

我的处理方式是:

1.定义SignInterceptor类实现Interceptor

import android.util.Log;

import java.io.IOException;
import java.util.Iterator;
import java.util.TreeMap;

import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import qgcp.com.get.util.MD5;


/**
 * Created  16/12/7 15:28.
 */
public class SignInterceptor implements Interceptor {

    public SignInterceptor() {}

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

          Request request = chain.request();
        String timestamp = Long.toString(System.currentTimeMillis() / 1000);
        //拼接timestamp
        String url = request.url().toString() + "&timestamp=" + timestamp;
        //获取参数列表
        String[] parts = url.split("\\?");
        //TreeMap里面的数据会按照key值自动升序排列
        TreeMap<String, String> param_map = new TreeMap<String, String>();
        //获取参数对
        String[] param_pairs = parts[1].split("&");
        for (String pair : param_pairs) {
            String[] param = pair.split("=");
            if (param.length != 2) {
                //没有value的参数不进行处理
                continue;
            }
            param_map.put(param[0], param[1]);
        }
        StringBuilder sign = new StringBuilder();
        Iterator it = param_map.keySet().iterator();
        //拼接参数
        while (it.hasNext()) {
            String key = it.next().toString();
            String value = param_map.get(key).toString();
            sign.append(key + value);
        }
        //Base64加密
        String sign_s = android.util.Base64.encodeToString(sign.toString().getBytes(), android.util.Base64.NO_WRAP);
        //Md5加密
        sign_s = MD5.GetMD5Code(sign_s);
        //重新拼接url
        HttpUrl.Builder httpUrlBuilder = request.url().newBuilder();
        //添加参数
        httpUrlBuilder.addQueryParameter("sign", sign_s);
        httpUrlBuilder.addQueryParameter("timestamp", timestamp);
        Request.Builder requestBuilder = request.newBuilder();
        requestBuilder.url(httpUrlBuilder.build());
        request = requestBuilder.build();
        return chain.proceed(request);
    }

}

2.导入到okhttp中

  SignInterceptor signInterceptor=new SignInterceptor();
  //配置log打印拦截器
  HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
  loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
  builder.addInterceptor(loggingInterceptor)
  .addInterceptor(signInterceptor)
  .retryOnConnectionFailure(false)
  .addNetworkInterceptor(loggingInterceptor);

md5工具类 和后端保持一致即可

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;


/**
 * MD5工具类
*/
public class MD5 {



    private final static String[] strDigits = { "0", "1", "2", "3", "4", "5",
            "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };

    public MD5() {
    }

    private static String byteToArrayString(byte bByte) {
        int iRet = bByte;
        // System.out.println("iRet="+iRet);
        if (iRet < 0) {
            iRet += 256;
        }
        int iD1 = iRet / 16;
        int iD2 = iRet % 16;
        return strDigits[iD1] + strDigits[iD2];
    }

    private static String byteToNum(byte bByte) {
        int iRet = bByte;
        System.out.println("iRet1=" + iRet);
        if (iRet < 0) {
            iRet += 256;
        }
        return String.valueOf(iRet);
    }

    private static String byteToString(byte[] bByte) {
        StringBuffer sBuffer = new StringBuffer();
        for (int i = 0; i < bByte.length; i++) {
            sBuffer.append(byteToArrayString(bByte[i]));
        }
        return sBuffer.toString();
    }

    public static String GetMD5Code(String strObj) {
        String resultString = null;
        try {
            resultString = new String(strObj);
            MessageDigest md = MessageDigest.getInstance("MD5");
            resultString = byteToString(md.digest(strObj.getBytes()));
        } catch (NoSuchAlgorithmException ex) {
            ex.printStackTrace();
        }
        return resultString;
    }
}

完结-------

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值