Logging with Retrofit 2

前端 未结 21 1326
春和景丽
春和景丽 2020-11-22 07:33

I\'m trying to get the exact JSON that is being sent in the request. Here is my code:

OkHttpClient client = new OkHt         


        
相关标签:
21条回答
  • 2020-11-22 08:05

    The main problem which I faced was dynamical adding headers and logging them into debug logcat. I've tried to add two interceptors. One for logging and one for adding headers on-the-go (token authorization). The problem was that we may .addInterceptor or .addNetworkInterceptor. As Jake Wharton said to me: "Network interceptors always come after application interceptors. See https://github.com/square/okhttp/wiki/Interceptors". So here is working example with headers and logs:

    OkHttpClient httpClient = new OkHttpClient.Builder()
                //here we can add Interceptor for dynamical adding headers
                .addNetworkInterceptor(new Interceptor() {
                    @Override
                    public Response intercept(Chain chain) throws IOException {
                        Request request = chain.request().newBuilder().addHeader("test", "test").build();
                        return chain.proceed(request);
                    }
                })
                //here we adding Interceptor for full level logging
                .addNetworkInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
                .build();
    
        Retrofit retrofit = new Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create(gsonBuilder.create()))
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .client(httpClient)
                .baseUrl(AppConstants.SERVER_ADDRESS)
                .build();
    
    0 讨论(0)
  • 2020-11-22 08:05

    hey guys,i already find solution:

      public static <T> T createApi(Context context, Class<T> clazz, String host, boolean debug) {
        if (singleton == null) {
            synchronized (RetrofitUtils.class) {
                if (singleton == null) {
                    RestAdapter.Builder builder = new RestAdapter.Builder();
                    builder
                            .setEndpoint(host)
                            .setClient(new OkClient(OkHttpUtils.getInstance(context)))
                            .setRequestInterceptor(RequestIntercepts.newInstance())
                            .setConverter(new GsonConverter(GsonUtils.newInstance()))
                            .setErrorHandler(new ErrorHandlers())
                            .setLogLevel(debug ? RestAdapter.LogLevel.FULL : RestAdapter.LogLevel.NONE)/*LogLevel.BASIC will cause response.getBody().in() close*/
                            .setLog(new RestAdapter.Log() {
                                @Override
                                public void log(String message) {
                                    if (message.startsWith("{") || message.startsWith("["))
                                        Logger.json(message);
                                    else {
                                        Logger.i(message);
                                    }
                                }
                            });
                    singleton = builder.build();
                }
            }
        }
        return singleton.create(clazz);
    }
    
    0 讨论(0)
  • 2020-11-22 08:06

    You can also add Facebook's Stetho and look at the network traces in Chrome: http://facebook.github.io/stetho/

    final OkHttpClient.Builder builder = new OkHttpClient.Builder();
    if (BuildConfig.DEBUG) {
        builder.networkInterceptors().add(new StethoInterceptor());
    }
    

    Then open "chrome://inspect" in Chrome...

    0 讨论(0)
  • 2020-11-22 08:08

    Here is an Interceptor that logs both the request and response bodies (using Timber, based on an example from the OkHttp docs and some other SO answers):

    public class TimberLoggingInterceptor implements Interceptor {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
    
            long t1 = System.nanoTime();
            Timber.i("Sending request %s on %s%n%s", request.url(), chain.connection(), request.headers());
            Timber.v("REQUEST BODY BEGIN\n%s\nREQUEST BODY END", bodyToString(request));
    
            Response response = chain.proceed(request);
    
            ResponseBody responseBody = response.body();
            String responseBodyString = response.body().string();
    
            // now we have extracted the response body but in the process
            // we have consumed the original reponse and can't read it again
            // so we need to build a new one to return from this method
    
            Response newResponse = response.newBuilder().body(ResponseBody.create(responseBody.contentType(), responseBodyString.getBytes())).build();
    
            long t2 = System.nanoTime();
            Timber.i("Received response for %s in %.1fms%n%s", response.request().url(), (t2 - t1) / 1e6d, response.headers());
            Timber.v("RESPONSE BODY BEGIN:\n%s\nRESPONSE BODY END", responseBodyString);
    
            return newResponse;
        }
    
        private static String bodyToString(final Request request){
    
            try {
                final Request copy = request.newBuilder().build();
                final Buffer buffer = new Buffer();
                copy.body().writeTo(buffer);
                return buffer.readUtf8();
            } catch (final IOException e) {
                return "did not work";
            }
        }
    }
    
    0 讨论(0)
  • 2020-11-22 08:10

    I found way for Print Log in Retrofit

    OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .addInterceptor(new Interceptor() {
                    @Override
                    public Response intercept(Chain chain) throws IOException {
                        Request request = chain.request();
                        if (BuildConfig.DEBUG) {
                            Log.e(getClass().getName(), request.method() + " " + request.url());
                            Log.e(getClass().getName(), "" + request.header("Cookie"));
                            RequestBody rb = request.body();
                            Buffer buffer = new Buffer();
                            if (rb != null)
                                rb.writeTo(buffer);
                            LogUtils.LOGE(getClass().getName(), "Payload- " + buffer.readUtf8());
                        }
                        return chain.proceed(request);
                    }
                })
                .readTimeout(60, TimeUnit.SECONDS)
                .connectTimeout(60, TimeUnit.SECONDS)
                .build();
    
                iServices = new Retrofit.Builder()
                        .baseUrl("Your Base URL")
                        .client(okHttpClient)
                        .addConverterFactory(GsonConverterFactory.create())
                        .build()
                        .create(Your Service Interface .class);
    

    Works for me.

    0 讨论(0)
  • 2020-11-22 08:19

    Try this:

    Request request = chain.request();
    Buffer buffer = new Buffer();
    request.body().writeTo(buffer);
    String body = buffer.readUtf8();
    

    After this, in the body there is the JSON you are interested in.

    0 讨论(0)
提交回复
热议问题