难点:获取已有的键值对
目标:获取已有的键值对,组成字符串加密后,新增一个字段signature,值为加密后的字符串。
import android.support.annotation.NonNull;
import android.support.v4.util.ArrayMap;
import com.linkfun.mpos.util.SignUtil;
import java.io.IOException;
import java.util.List;
import java.util.Set;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
/**
* 对已有的接口多添加一个签名字段
*
* @author jdallen
* @since 2019/4/2
*/
public class AddParameterInterceptor implements Interceptor {
@Override
public Response intercept(@NonNull Chain chain) throws IOException {
Request oldRequest = chain.request();
HttpUrl oldHttpUrl = oldRequest.url();
//构建签名字段的值
ArrayMap<String, String> signParams = new ArrayMap<>();
//todo 现仅支持Get方法
if (oldRequest.method().equals("GET")) {
Set<String> nameList = oldHttpUrl.queryParameterNames();//获取所有的键
for (String name : nameList) {
List<String> valueList = oldHttpUrl.queryParameterValues(name);//获取指定键名的值
if (null != valueList && valueList.size() > 0) {
signParams.put(name, valueList.get(0));
} else {
signParams.put(name, null);
}
}
}
String signature = SignUtil.signMap(signParams);
//新增签名字段
HttpUrl url = oldHttpUrl.newBuilder()
.addQueryParameter("signature", signature)
.build();
// Request customization: add request headers
Request.Builder requestBuilder = oldRequest.newBuilder().url(url);
return chain.proceed(requestBuilder.build());
}
}
网友评论