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

3
我正在使用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'

请将这个代码 httpClient.interceptors().add(interceptor); 替换为 httpClient.add(interceptor); 并告诉我。 - Aishwarya Tiwari
不行,结果相同 - Jemo Mgebrishvili
3个回答

4

请尝试按以下方式使用OkHttpClient:

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

然后将其设置为您的Retrofit构建器:

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

3

像这样进行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> S createService(Class<S> serviceClass) {
    return provideRestAdapter().create(serviceClass);
}

}

登录服务接口

public interface LoginService {

/**
 * To Post FormUrlEncoded to web service
 *
 * @return Call Object of Type JsonObject
 */

@FormUrlEncoded
@POST("api/login")
Call<JsonObject> 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<JsonObject> call = loginService.login(edtEmail.getText().toString(),edtPassword.getText().toString(),mDeviceType,mDeviceToken);
    call.enqueue(new Callback<JsonObject>() {
        @Override
        public void onResponse(Call<JsonObject> call, Response<JsonObject> 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<JsonObject> call, Throwable t) {
            hideProgressDialog();
            LOGD(TAG, "onFailure: " + t.getMessage());
        }
    });
}

登录响应 根据您的需求进行更改。

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;
    }

}
}

祝你愉快!


2
我认为在使用Builder创建客户端时添加拦截器会更好,如下所示的代码。如果您注意到,我们添加了两个拦截器: -网络拦截器> addNetworkInterceptor -拦截器> addInterceptor 主要区别是网络拦截器仅在有实际请求(而不是从缓存加载)时才起作用。拦截器记录从网络或缓存加载的数据。
还要确保导入了正确的BuildConfig(有时自动完成会从其中一个库中导入它,然后它将始终为false)。
`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);
    }

`


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接