othttp添加請求公共參數(shù)的幾種方法
第一種 添加在請求鏈接尾部
HttpUrl url = original.url().newBuilder() //請求尾部鏈接
.addQueryParameter(VERSION, "")
.addQueryParameter(APP_VERSION, "")
.addQueryParameter(DEVICE, "")
.addQueryParameter(DEVICE_NAME, "android")
.addQueryParameter(DEVICE_IMEI, "")
.addQueryParameter(OS_VERSION, "")
.addQueryParameter(TOKEN, "")
.addQueryParameter(DEVICE_ID, "")
.build();
Request request = original.newBuilder()
.method(original.method(), original.body())
//添加到請求里
.url(url)
.build();
第二種 添加在請求form表單里
最麻煩的一種,一般情況下不會(huì)用這種方法
RequestBody formBody = new FormBody.Builder()//form表單
.add(DEVICE_ID, "")
.add(CHANNEL, "")
.add(DEVICE_SERIAL_ID, "")
.add(MOBILE_OS, "android")
.add(VERSION, "")
.add(MEMBER_ID, "")
.add(MEMBER_TYPE, "")
.add(TOKEN, "")
.build();
//默認(rèn)添加formBody后不能添加新的form表單宾抓,需要先將RequestBody轉(zhuǎn)成string去拼接
String postBodyString = bodyToString(original.body());
postBodyString += ((postBodyString.length() > 0) ? "&" : "") + bodyToString(formBody);
Request request = original.newBuilder()
.method(original.method(), original.body())
//添加到請求里
//string轉(zhuǎn)回成RequestBody
.post(RequestBody.create(MediaType.parse("application/x-www-form-urlencoded"),
postBodyString))
.build();
RequestBody轉(zhuǎn)String的方法
private static String bodyToString(final RequestBody request){
try {
final RequestBody copy = request;
final Buffer buffer = new Buffer();
if(copy != null)
copy.writeTo(buffer);
else
return "";
return buffer.readUtf8();
}
catch (final IOException e) {
return "did not work";
}
}
第三種 添加在請求head
Request request = original.newBuilder()
.method(original.method(), original.body())
.addHeader(DEVICE_ID, "")
.addHeader(CHANNEL, "")
.addHeader(DEVICE_SERIAL_ID, "")
.addHeader(MOBILE_OS, "android")
.addHeader(VERSION, "")
.addHeader(MEMBER_ID, "")
.addHeader(TOKEN, "")
.addHeader(MEMBER_TYPE, "")
.build();