用于http请求和响应日志记录的HttpLoggingInterceptor

我正在使用retrofit2,我需要记录所有请求和响应。 请求和响应工作完美,我只需要记录这些请求/响应,我尝试了几乎所有解决方案,我在这里找到,但没有找到解决方案。 我不明白这里有什么不对

这是我的代码

class Factory { private final static OkHttpClient.Builder httpClient = new OkHttpClient.Builder(); private static NetworkApi.Factory serverApi; private static HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(); private Retrofit retrofit = new Retrofit.Builder() .baseUrl(RequestApi.BASE_URL) .client(httpClient.build()) .addConverterFactory(GsonConverterFactory.create()) .build(); public static NetworkApi getApi() { if (BuildConfig.DEBUG){ interceptor.setLevel(HttpLoggingInterceptor.Level.BODY); httpClient.addInterceptor(new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { Request.Builder builder = chain.request().newBuilder() .addHeader("Content-Type", "application/json"); return chain.proceed(builder.build()); } }); httpClient.interceptors().add(interceptor); } if (serverApi == null){ serverApi = new NetworkApi.Factory(); } return serverApi.retrofit.create(NetworkApi.class); } } 

图书馆:

 compile 'com.google.code.gson:gson:2.7' compile 'com.squareup.retrofit2:retrofit:2.1.0' compile 'com.squareup.retrofit2:converter-gson:2.1.0' compile 'com.squareup.okhttp3:okhttp:3.6.0' compile 'com.squareup.okhttp3:logging-interceptor:3.6.0' 

尝试使用OkHttpClient,如下所示:

 private OkHttpClient createDefaultOkHttpClient() { HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(); interceptor.setLevel(HttpLoggingInterceptor.Level.BODY); return new OkHttpClient().newBuilder() .addInterceptor(interceptor) .build(); } 

然后将其设置为您的改造生成器:

 Retrofit retrofitAsync = new Retrofit.Builder() .baseUrl(BASE_URL_APPS) .client(createDefaultOkHttpClient()) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(rxAdapter) .build(); 

像这样进行API调用。

ApiFactory.java

 public class ApiFactory { /** * Base URL for API calls */ private static final String BASE_URL = ""; public ApiFactory() { } private static Retrofit provideRestAdapter() { return new Retrofit.Builder() .baseUrl(BASE_URL) .client(BaseApplication.getInstance().getOkHttpClient()) .addConverterFactory(GsonConverterFactory.create()) .addConverterFactory(ScalarsConverterFactory.create()) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .build(); } public static  S createService(Class serviceClass) { return provideRestAdapter().create(serviceClass); } 

}

LoginService接口

 public interface LoginService { /** * To Post FormUrlEncoded to web service * * @return Call Object of Type JsonObject */ @FormUrlEncoded @POST("api/login") Call login(@Field("email") String email, @Field("password") String password, @Field("devicetype") String devicetype, @Field("deviceid") String deviceid); } 

在这里进行API调用

 private void emailLoginRequest() { LoginService loginService = ApiFactory.createService(LoginService.class); Call call = loginService.login(edtEmail.getText().toString(),edtPassword.getText().toString(),mDeviceType,mDeviceToken); call.enqueue(new Callback() { @Override public void onResponse(Call call, Response response) { hideProgressDialog(); if (response.isSuccessful()) { LOGD(TAG, "onResponse 0: " + response.body().toString()); LoginResponse loginResponse = new Gson().fromJson(response.body().toString(), LoginResponse.class); System.out.println("+++ get message >> " + loginResponse.getMessage()); int status = loginResponse.getStatus(); }else { LOGD(TAG, "response fail 0: " + response.body()); } } @Override public void onFailure(Call call, Throwable t) { hideProgressDialog(); LOGD(TAG, "onFailure: " + t.getMessage()); } }); } 

LoginResponse按照您的要求进行更改。

 public class LoginResponse { @SerializedName("status") @Expose private Integer status; @SerializedName("message") @Expose private String message; @SerializedName("data") @Expose private Data data; /** * No args constructor for use in serialization * */ public LoginResponse() { Sample response model // { // "status": 1, // "data": { // "user_id": "565464564", // "email": "email@email.com", // "fullname": "james", // "username": "james123", // "country": "54654654", // "city": "56546465546", // "token": "dfgdfgdfg545465465464564" // }, // "message": "Login successfull" // } } /** * * @param message * @param status * @param data */ public LoginResponse(Integer status, String message, Data data) { this.status = status; this.message = message; this.data = data; } /** * * @return * The status */ public Integer getStatus() { return status; } /** * * @param status * The status */ public void setStatus(Integer status) { this.status = status; } /** * * @return * The message */ public String getMessage() { return message; } /** * * @param message * The message */ public void setMessage(String message) { this.message = message; } /** * @return The data */ public Data getData() { return data; } /** * @param data The data */ public void setData(Data data) { this.data = data; } public class Data { @SerializedName("user_id") @Expose private String userId; @SerializedName("email") @Expose private String email; /** * No args constructor for use in serialization */ public Data() { } /** * @param email * @param userId */ public Data(String userId, String email) { this.userId = userId; this.email = email; } /** * @return The userId */ public String getUserId() { return userId; } /** * @param userId The user_id */ public void setUserId(String userId) { this.userId = userId; } /** * @return The email */ public String getEmail() { return email; } /** * @param email The email */ public void setEmail(String email) { this.email = email; } } } 

请享用!

我最好在使用Builder创建客户端时添加拦截器,如下面的代码。 如果你注意到我们添加了两个拦截器 – 网络拦截器> addNetworkInterceptor – 拦截器> addInterceptor

主要区别是网络拦截器仅在存在实际请求时才起作用(不从缓存加载)。 从网络或缓存加载的两种情况下的拦截器日志数据。

还要确保你正在使用正确的Bui​​ldConfig(有时自动完成从你的一个库中导入它,然后它总是假的)

 `OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder(); if (BuildConfig.DEBUG) { HttpLoggingInterceptor.Logger networkLayerLogger = new HttpLoggingInterceptor.Logger() { @Override public void log(String message) { LogUtils.d("NetworkLayer", message); } }; HttpLoggingInterceptor.Logger appLayerLogger = new HttpLoggingInterceptor.Logger() { @Override public void log(String message) { LogUtils.d("ApplicationLayer", message); } }; HttpLoggingInterceptor networkLogging = new HttpLoggingInterceptor(networkLayerLogger); HttpLoggingInterceptor appLogging = new HttpLoggingInterceptor(appLayerLogger); networkLogging.setLevel(HttpLoggingInterceptor.Level.HEADERS); appLogging.setLevel(HttpLoggingInterceptor.Level.BODY); clientBuilder.addNetworkInterceptor(networkLogging); clientBuilder.addInterceptor(appLogging); } 

`