由于我需要使用Retrofit 2,我需要记录请求背后发生的事情,因此解决方案是添加请求拦截器。我添加了一个来自okhttp wiki 的拦截器,我还根据需要添加了一些其他更改,并在构建阶段将其设置为okhttp客户端,但它没有按照我的预期工作。当我将自定义拦截器设置为okhttp客户端时,GsonConverter无法将响应json解析为java对象。
以下是拦截器
的代码public class LoggingInterceptor implements Interceptor {
private final static String TAG = "RI";
private HashMap<String, String> headersMap = null;
public LoggingInterceptor(HashMap<String, String> headers) {
this.headersMap = headers;
}
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
Request.Builder reqBuilder = request.newBuilder();
Log.e(TAG, "Headers on the map -> " + headersMap.size());
for (String header : headersMap.keySet()) {
reqBuilder.addHeader(header, headersMap.get(header));
}
request = reqBuilder.build();
long timeRequest = System.nanoTime();
Log.d(TAG, String.format(Locale.getDefault(), "Sending %s with %s", request.url(), request.headers()));
Response response = chain.proceed(request);
Log.d(TAG, "<<<=========================================>>>");
long timeResponse = System.nanoTime();
Log.d(TAG, String.format(Locale.getDefault(), "Receiving %s in %s%n%s", response.request().url(), ((timeResponse - timeRequest)/1e6d), response.headers()));
Log.d(TAG, "Data: " + response.body().string());
Log.d(TAG, "Code: " + response.code());
return response;
}
}
以下是我如何将它添加到Okhttp客户端
private OkHttpClient createHttpClient(){
if(client == null){
String strUserAgent = "tm-vc=" + BuildConfig.VERSION_CODE + "-devid=" + (getDeviceID().isEmpty() ? "0" : getDeviceID());
HashMap<String, String> headers = new HashMap<>();
headers.put(HEADER_ACCEPT, "application/json; charset=utf-8");
headers.put(HEADER_USER_AGENT, strUserAgent);
String cookie = getSessionCookie();
if(cookie != null && !cookie.isEmpty())
headers.put(HEADER_COOKIE, cookie);
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.addInterceptor(new LoggingInterceptor(headers));
builder.retryOnConnectionFailure(true);
client = builder.build();
}
return client;
}
为了测试我所说的,我只需要评论这一行builder.addInterceptor(new LoggingInterceptor(headers));
,如果你对该行进行评论,则会调用onResponse的改进并成功(工作,json被解析),如果不是onFailure则被调用。
那么我在拦截器实现上缺少什么?
问题本身是什么? 如何使用拦截器向请求添加标题?
是的,我可以使用注释,但标题的值将是静态的。
注意:我正在使用完全更新的Retrofit 2.
答案 0 :(得分:1)
您可以将 HttpLoggingInterceptor 与 Retrofit 2 一起使用,如下所示
1)Api客户
// imports
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
---
// Method to create instance of Service
public ApiService getService() {
// Interceptor to Log the Request
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
// Level.BODY prints Urls, Params and Response
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
// Create the Client
OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();
// Initialize retrofit instance
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.build();
// Creates the instance of Web Service Representation
return retrofit.create(ApiService.class);
}
2)Gradle依赖
// Retrofit 2 dependency
compile 'com.squareup.retrofit2:retrofit:2.1.0'
// GSON for Parsing into POJOs
compile 'com.squareup.retrofit2:converter-gson:2.0.2'
// Logging Interceptor to Log the Request
compile 'com.squareup.okhttp3:logging-interceptor:3.4.1'
// OK HTTP dependency (for Compatibility)
compile 'com.squareup.okhttp3:okhttp:3.4.1'
3)同样,您可以将自己的自定义(例如,标题)添加到Retrofit