日志拦截器
compile 'com.squareup.okhttp3:logging-interceptor:3.3.0'
HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor()
httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY)
builder.addInterceptor(httpLoggingInterceptor)
Get请求统一追加参数
public class AppendUrlParamInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
HttpUrl.Builder builder = request.url().newBuilder();
HttpUrl newUrl = builder
.addQueryParameter("token", "iamtoken")
.build();
Request newRequest = request.newBuilder()
.url(newUrl)
.build();
return chain.proceed(newRequest);
}
}
public class AppendHeaderParamInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
Headers.Builder builder = request.
headers().
newBuilder();
Headers newHeader = builder
.add("header1", "iam header1")
.build();
Request newRequest = request.newBuilder()
.headers(newHeader)
.build();
return chain.proceed(newRequest);
}
}
Post请求body统一追加参数
public class AppenBodyParamsInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
RequestBody newBody = RequestBody.create(MediaType.parse("application/x-www-form-urlencoded")
, "token=iamtoken");
Request newRequest = request.newBuilder()
.post(newBody)
.build();
return chain.proceed(newRequest);
}
}