【问题标题】:HttpLoggingInterceptor for http request & response loggingHttpLoggingInterceptor 用于 http 请求和响应日志记录
【发布时间】:2017-08-07 16:48:34
【问题描述】:

我正在使用 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);让我知道。
  • 不,同样的结果

标签: java android retrofit2 okhttp3


【解决方案1】:

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

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

还要确保您正在 imorting 正确的 BuildConfig(有时自动完成从您的库之一导入它,那么它总是错误的)

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

`

【讨论】:

    【解决方案2】:

    像这样进行 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());
            }
        });
    }
    

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

    享受吧!

    【讨论】:

      【解决方案3】:

      尝试使用 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();
      

      【讨论】:

        猜你喜欢
        • 2022-01-08
        • 2012-09-12
        • 1970-01-01
        • 2022-06-21
        • 1970-01-01
        • 2018-12-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多