添加统一的请求参数、请求头 :是通过拦截器来完成的:
拦截器:
private Interceptor netCacheInterceptor = new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
HttpUrl httpUrl = request.url()
.newBuilder()
// add common parameter
.addQueryParameter("token", "123")
.addQueryParameter("username", "xiaocai")
.build();
Request build = request.newBuilder()
// add common header
.addHeader("contentType", "text/json")
.url(httpUrl)
.build();
Response response = chain.proceed(build);
return response;
}
};
Request:是一个builder模式,执行的是product的角色。而其中的builder承担着builder、concreteBuilder、director的角色。
chain是okhttp的网络请求者,可以获取request以及发起请求process
okhttp添加拦截器:
private void initOkHttpClient() {
OkHttpClient.Builder builder = new OkHttpClient.Builder();
if (ApiClient.DEBUG) {
// Log信息拦截器
HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
//设置 Debug Log 模式
builder.addNetworkInterceptor(loggingInterceptor);
}
//设置超时
builder.connectTimeout(15, TimeUnit.SECONDS);
builder.readTimeout(20, TimeUnit.SECONDS);
builder.writeTimeout(20, TimeUnit.SECONDS);
//错误重连
builder.retryOnConnectionFailure(true);
// commen parameter
builder.addInterceptor(netCacheInterceptor);
mOkHttpClient = builder.build();
}
服务器代码:
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Enumeration<String> parameterNames = request.getParameterNames();
while(parameterNames.hasMoreElements()){
String nextElement = parameterNames.nextElement();
String value = request.getParameter(nextElement);
System.out.println("nextElement:"+nextElement+" value:"+value);
}
Enumeration<String> headerNames = request.getHeaderNames();
while(headerNames .hasMoreElements()){
String nextElement = headerNames.nextElement();
String header = request.getHeader(nextElement);
System.out.println("key:"+nextElement+" value:"+header);
}
}
服务器得到的结果:
nextElement:username value:xiaocai
nextElement:token value:123
nextElement:loginPassword value:1
nextElement:mobile value:1
key:contenttype value:text/json
key:content-type value:application/x-www-form-urlencoded
key:content-length value:62
key:host value:10.0.2.2:8080
key:connection value:Keep-Alive
key:accept-encoding value:gzip
key:user-agent value:okhttp/3.6.0