Retrofit 2使用HttpLoggingInterceptor.Level.BODY在日志中打印空响应主体

时间:2016-03-16 12:39:15

标签: android retrofit2

我使用Retrofit 2.0.0。这是构建我的HTTP客户端的代码

protected OkHttpClient getHttpClient(){
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.addInterceptor(
                chain -> {
                    Request original = chain.request();

                    Request.Builder requestBuilder = original.newBuilder();

                    requestBuilder.header("Accept-Language", App.getInstance().getPrefs().getSelectedLanguage().toLowerCase());
                    requestBuilder.header("Accept-Encoding", "gzip");

                    if(API.this instanceof PrivateAPI){
                        LoginResponse loginResponse = AuthManager.getInstanse().getLoginResponse();
                        requestBuilder.header("Authorization", String.format("%s %s",
                                loginResponse.getTokenType(),
                                loginResponse.getAccessToken()));
                    }

                    requestBuilder.method(original.method(), original.body());

                    Request request = requestBuilder.build();
                    return chain.proceed(request);
                });

        if(BuildConfig.DEBUG){
            HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
            loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            builder.addInterceptor(loggingInterceptor);
        }

        return builder.build();
    }

以下是我如何使用它来启动我的Retrofit API接口:

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(BASE_URL)
            .addConverterFactory(GsonConverterFactory.create(getGson()))
            .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
            .client(getHttpClient())
            .build();

    apiService = retrofit.create(PrivateAPIInterface.class);

直到昨天,我正在按原样登录logcat。但突然间,我开始在我的日志中找到空的响应主体。以下是我现在获得的日志示例:

  D/OkHttp: --> GET http://MY_DOMAIN/utility/gaz?branchid=&phone=21919&customerid= HTTP/1.1
  D/OkHttp: Accept-Language: hy
  D/OkHttp: Accept-Encoding: gzip
  D/OkHttp: Authorization: 0yXK65Go_hRPT32WIP4DAKjmzIaM0riSLlybHhusvwmYJSxTdTVBrkL5CaqopXgrOuNFL5xvR5uVwCbprWrxvfYTMJ1I_AUmd5TKdNL4ptkUrJuOy1kGiule_yveCFv0GbTiAXhYjdfynJICJEVWc54ibnIv_Q14dLpPuVle5IaRuHmza2Pavkrhzi42sfMsK0Qpxaueu8eRPysk6MP9WkTnSKYIAThuq3sHq8RGAnkaLBx
  D/OkHttp: --> END GET
  D/OkHttp: <-- 200 OK http://MY_DOMAIN/utility/gaz?branchid=&phone=21919&customerid= (394ms)
  D/OkHttp: Content-Length: 8527
  D/OkHttp: Content-Type: application/json; charset=utf-8
  D/OkHttp: Server: Microsoft-IIS/7.5
  D/OkHttp: X-Powered-By: ASP.NET
  D/OkHttp: Date: Wed, 16 Mar 2016 12:30:37 GMT
  D/OkHttp: OkHttp-Sent-Millis: 1458131438086
  D/OkHttp: OkHttp-Received-Millis: 1458131438438
  D/OkHttp: }
  D/OkHttp: <-- END HTTP (8527-byte body)

正如你所看到的,我得到的一切都是D/OkHttp: }。 但是在Postman中我看到一个正常的响应体,在我的应用程序中一切正常,所以问题只在于记录。

任何人都可以帮助我理解为什么会发生这种情况吗?

P.S。如果请求具有正文,我会看到请求正文,问题仅在于响应bodys。

2 个答案:

答案 0 :(得分:6)

使用retrofit-2,您应该使用 OkHttp3 来获取完整日志。将此添加到您的家属:compile 'com.squareup.okhttp3:logging-interceptor:3.0.1'

HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();

Retrofit retrofit = new Retrofit.Builder()
        .baseUrl("https://example.com")
        .client(client)
        .addConverterFactory(GsonConverterFactory.create())
        .build();

return retrofit.create(ApiClient.class);

答案 1 :(得分:1)

ResClient.class

 public class RestClient {

        private static ApiInterface apiInterface;

        static {
            setupRestClient();
        }

        private static void setupRestClient() {
            OkHttpClient httpClient = new OkHttpClient();

            RestAdapter restAdapter = new RestAdapter.Builder()
                                      .setEndpoint(NetworkConstants.URL_BASE_LIVE)
                                      .setLogLevel(RestAdapter.LogLevel.FULL)
                                      .setLog(new AndroidLog("Retrofit"))
                                      .setClient(new OkClient(httpClient))
                                      .build();

            apiInterface = restAdapter.create(ApiInterface.class);
        }


        public static ApiInterface getAdapter(){
                return apiInterface;
        }
    }

ApiInterface.class

public interface ApiInterface {


    // result api
    //All result api async
    @Headers({"Authorization: ######################"}) //for the header authorization if needed.
    @GET(NetworkConstants.URL_GET_RESULTS)
    void getResult(@QueryMap Map <String, String> params, Callback<ArrayList<Results>> callback);
}

现在称之为

// Fetching result through Api Hit   
        RestClient.getAdapter().getResult(getJobsParams(), new Callback<ArrayList<Result>>() {

            @Override
            public void success(ArrayList<Result> result, retrofit.client.Response response) {
                   // Do your Work
            }

            @Override
            public void failure(RetrofitError error) {
                   // show server or other error to user
            }
        });