OkHttp - 启用日志

Jul*_*Jul 18 android web-services http okhttp

我使用Retrofit来发出Http请求和Json解析,我喜欢打开调试日志的方法.日志允许查看正文请求,网址...这非常有用.由于Retrofit使用OkHttp,我想知道OkHttp是否也有办法为每个请求启用日志.

Jam*_*ken 26

使用a Interceptor,您可以定义以下类:

class LoggingInterceptor implements Interceptor {
  @Override public Response intercept(Chain chain) throws IOException {
    Request request = chain.request();

    long t1 = System.nanoTime();
    Log.d("OkHttp", String.format("Sending request %s on %s%n%s",
        request.url(), chain.connection(), request.headers()));

    Response response = chain.proceed(request);

    long t2 = System.nanoTime();
    Log.d("OkHttp", String.format("Received response for %s in %.1fms%n%s",
        response.request().url(), (t2 - t1) / 1e6d, response.headers()));

    return response;
  }
}
Run Code Online (Sandbox Code Playgroud)

并添加它:

OkHttpClient client = new OkHttpClient.Builder()
  .addInterceptor(new LoggingInterceptor())
  .build();
Run Code Online (Sandbox Code Playgroud)


sea*_*ato 14

拦截器功能目前正在审核中,但您可以通过在拉取请求中应用代码更改来构建您自己的okHttp版本.

您可以使用此类功能实现所需的功能

// 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);
Run Code Online (Sandbox Code Playgroud)

如果您想查看更多内容,则拉取请求中会包含测试.

我将不得不提前警告你使用它.拦截器API可能有变化,因为它尚未合并.不要将它与生产代码一起使用,但它对于个人测试来说无害.


Jes*_*son 7

还没有.但是正在开发的拦截器功能应该可以让它变得简单.


Hoa*_*Huu 5

现在有来自 Square(员工)的官方解决方案。你可以试试:https : //github.com/square/okhttp/tree/master/okhttp-logging-interceptor