1、添加Header
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
//添加Log
httpClient.addNetworkInterceptor(getInterceptor(true));
//添加固定的header参数
httpClient.readTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);
httpClient.connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);
httpClient.writeTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);
//针对不同的情况写 Log
private HttpLoggingInterceptor getInterceptor(boolean debug) { HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(); if (debug) { interceptor.setLevel(HttpLoggingInterceptor.Level.BODY); // 测试 } else { interceptor.setLevel(HttpLoggingInterceptor.Level.NONE); // 打包 } return interceptor; }
//添加动态的Header
httpClient.addInterceptor(new HttpHeadInterceptor());
private class HttpHeadInterceptor implements Interceptor { public HttpHeadInterceptor() { } @Override public okhttp3.Response intercept(Chain chain) throws IOException { Request originalRequest = chain.request(); Request.Builder requestBuilder = originalRequest.newBuilder(); requestBuilder.addHeader("time", "时间");
//添加User-Agent String user = HttpHead.getUserAgent(); requestBuilder.addHeader("User-Agent", user); Request request = requestBuilder.build(); okhttp3.Response response = chain.proceed(request);
//获取response的header String responseHeadTime = response.header("time").toString();return response; } }
2、生成Retrofit对象
Retrofit retrofit = new Retrofit.Builder() .baseUrl("http://xxxxxxxxxxxxxxxxxxxx") .client(httpClient.build()) .addConverterFactory(GsonConverterFactory.create(date, httpHeadInfo)) .build();
GsonConverterFactory是附加器(按照设计模式,好像是AOP,面向切面编程)
3、body加密的时候,写在GsonConverterFactory的 requestBodyConverter 里
注意,相对于ASP.Net mvc来说,接口里边传入@Body的话呢,在服务器端是接收不到的。你需要把这些东西通过 FormBody重新赋值一下
@Override public RequestBody convert(T value) throws IOException { if (value instanceof BaseSign) { String jsonstr = gson.toJson(value); String key = "android"; Logger.debug("xxx", "AES加密前:" + jsonstr + " key=" + key); key = Md5Util.parseStrToMd5L32(key); String newRequest = AESUtils.initEncode(jsonstr, key); return new FormBody.Builder().add("data", newRequest).build(); } else { //这里是不加密的 return RequestBody.create(MEDIA_TYPE, ""); }