OkhttpのPostリクエストパラメータをInterceptorで変更

26062 ワード

に注意


マスターブックのokhttpとrxJavaに基づいて、このブログは新版のokhttpとrxJava、retrofitに適していない可能性があります.
Androidはrxjava+retrofit+okhttpを使用する場合、リクエストパラメータを再処理する必要がある場合があります.すべてのインタフェースには、デフォルトでsign、timestamp 2パラメータが必要です.sign:パラメータ名+パラメータ値接合の後、base 64符号化を行い、md 5暗号化(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);

md 5ツールクラスとバックエンドは一致すればよい
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;
    }
}

終了------