Search code examples
androidweb-serviceshttpokhttp

OkHttp - Enable logs


I used Retrofit in order to make HTTP requests and JSON parsing and I loved the way to turn on debug logs. Logs allow to see body requests, URL... which is very useful. As Retrofit use OkHttp, I'm wondering if OkHttp also have a way to enable logs for each requests made.


Solution

  • The interceptors feature is currently in review, but you can build your own version of okHttp with the feature by applying the code changes in the pull request.

    You can implement the functionality you want with something like this

    // Create an interceptor which catches requests and logs the info you want
    RequestInterceptor logRequests= new RequestInterceptor() {
      public Request execute(Request request) {
        Log.i("REQUEST INFO", request.toString());
        return request; // return the request unaltered
      }
    };
    
    OkHttpClient client = new OkHttpClient();
    List<RequestInterceptor> requestInterceptors = client.requestInterceptors();
    requestInterceptros.add(logRequests);
    

    A test is included within the pull request if you want to see more.

    I'm going to have to warn you ahead of time about using this. There may be changes to the interceptor API since it has yet to be merged in. Don't use it with production code, but it's innocuous enough for personal testing.