348

我正在尝试获取在请求中发送的确切 JSON。这是我的代码:

OkHttpClient client = new OkHttpClient();
client.interceptors().add(new Interceptor(){
   @Override public com.squareup.okhttp.Response intercept(Chain chain) throws IOException {
      Request request = chain.request();
      Log.e(String.format("\nrequest:\n%s\nheaders:\n%s",
                          request.body().toString(), request.headers()));
      com.squareup.okhttp.Response response = chain.proceed(request);
      return response;
   }
});
Retrofit retrofit = new Retrofit.Builder()
   .baseUrl(API_URL)
   .addConverterFactory(GsonConverterFactory.create())
   .client(client).build();

但我只在日志中看到这一点:

request:
com.squareup.okhttp.RequestBody$1@3ff4074d
headers:
Content-Type: application/vnd.ll.event.list+json

考虑到我们过去使用 Retrofit 1的删除setLog()和使用,我应该如何进行正确的日志记录?setLogLevel()

4

22 回答 22

766

在 Retrofit 2 中,您应该使用HttpLoggingInterceptor

将依赖项添加到build.gradle. 截至 2019 年 10 月的最新版本是:

implementation 'com.squareup.okhttp3:logging-interceptor:4.2.1'

创建一个Retrofit如下所示的对象:

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

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

return retrofit.create(ApiClient.class);

如果出现弃用警告,只需更改setLevel为:

interceptor.level(HttpLoggingInterceptor.Level.BODY);

上述解决方案为您提供的 logcat 消息与设置的旧消息非常相似

setLogLevel(RestAdapter.LogLevel.FULL)

在以下情况下java.lang.ClassNotFoundException

较旧的改造版本可能需要较旧的logging-interceptor版本。查看评论部分了解详细信息。

于 2015-10-21T10:23:32.657 回答
38

我遇到了你的事情,我试图问这本书的作者 Retrofit: Love working with APIs on Android(这里是链接)(不!我不是为他们制作一些广告......但他们真的很好伙计们 :) 作者很快就回复了我,在 Retrofit 1.9 和 Retrofit 2.0-beta 上都有 Log 方法。

这是 Retrofit 2.0-beta 的代码:

HttpLoggingInterceptor logging = new HttpLoggingInterceptor();  
// set your desired log level
logging.setLevel(Level.BODY);

OkHttpClient httpClient = new OkHttpClient();  
// add your other interceptors …

// add logging as last interceptor
httpClient.interceptors().add(logging);  // <-- this is the important line!

Retrofit retrofit = new Retrofit.Builder()  
   .baseUrl(API_BASE_URL)
   .addConverterFactory(GsonConverterFactory.create())
   .client(httpClient)
   .build();

这是如何在HttpLoggingInterceptor的帮助下添加日志记录方法。另外,如果您是我上面提到的那本书的读者,您可能会发现它说 Retrofit 2.0 不再有 log 方法——我曾问过作者,这是不正确的,他们将在明年更新这本书关于它。

// 如果你对 Retrofit 中的 Log 方法不是很熟悉,我想再分享一些东西。

还应该注意,您可以选择一些日志记录级别。我大部分时间都使用Level.BODY ,它会给出这样的东西:

在此处输入图像描述

你可以在图片里面找到几乎所有的http人员:header、content和response等。

有时你真的不需要所有的客人都参加你的聚会:我只想知道它是否成功连接,我的 Activiy & Fragmetn 中是否成功拨打了互联网电话。然后你可以自由使用Level.BASIC,它会返回如下内容:

在此处输入图像描述

你能在里面找到状态码200 OK吗?这就对了 :)

还有另一个,Level.HEADERS,它只会返回网络的标题。雅当然是另一张照片:

在此处输入图像描述

这就是所有的日志记录技巧;)

我想和你分享我在那里学到很多的教程。他们有一堆很棒的帖子谈论几乎所有与 Retrofit 相关的内容,并且他们正在继续更新帖子,同时 Retrofit 2.0 即将到来。请看看那些工作,我认为这会节省你很多时间。

于 2015-12-12T06:25:11.790 回答
15

这是一个Interceptor记录请求和响应主体的日志(使用 Timber,基于 OkHttp 文档中的示例和其他一些 SO 答案):

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";
        }
    }
}
于 2015-09-26T19:12:22.690 回答
8

我面临的主要问题是动态添加标头并将它们记录到调试 logcat 中。我试图添加两个拦截器。一种用于记录,另一种用于在旅途中添加标头(令牌授权)。问题是我们可能会使用 .addInterceptor 或 .addNetworkInterceptor。正如 Jake Wharton 对我所说:“网络拦截器总是在应用程序拦截器之后出现。请参阅https://github.com/square/okhttp/wiki/Interceptors ”。所以这里是标题和日志的工作示例:

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();
于 2016-04-25T17:17:24.473 回答
7

尝试这个:

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

在此之后,body有您感兴趣的 JSON。

于 2015-09-17T14:33:36.433 回答
7

setLevel()当我试图用 HttpLoggingInterceptor 的实例调用它时,我也陷入了类似的情况,方法没有到来,如下所示:

HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

这是我解决它的方法,为 Retrofit2 生成日志,

我想你已经添加了依赖,

implementation "com.squareup.okhttp3:logging-interceptor:4.7.2"

有关最新版本,您可以查看此链接:

https://github.com/square/okhttp/tree/master/okhttp-logging-interceptor

在这里,他们还解释了如何添加。

我用 name 创建了一个类AddLoggingInterceptor,这是我的代码,

public class AddLoggingInterceptor {

    public static OkHttpClient setLogging(){
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .addInterceptor(loggingInterceptor)
                .build();

        return okHttpClient;
    }
}

然后,在我们实例化改造的地方,

 public static Retrofit getRetrofitInstance() {
    if (retrofit == null) {
        retrofit = new retrofit2.Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .client(AddLoggingInterceptor.setLogging()) // here the method is called inside client() method, with the name of class, since it is a static method.
                .build();
    }
    return retrofit;
}

现在你可以在你的 Android Studio 中看到生成的日志,你可能需要搜索,okHttp过滤过程。它对我有用。如果有任何问题可以在这里给我发短信。

于 2020-05-24T14:56:37.180 回答
6

如果您使用的是 Retrofit2 和 okhttp3,那么您需要知道 Interceptor 是按队列工作的。所以在你的其他拦截器之后添加 loggingInterceptor:

HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
        if (BuildConfig.DEBUG)
            loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.HEADERS);

 new OkHttpClient.Builder()
                .connectTimeout(60, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS)
                .writeTimeout(60, TimeUnit.SECONDS)
                .addInterceptor(new CatalogInterceptor(context))//first
                .addInterceptor(new OAuthInterceptor(context))//second
                .authenticator(new BearerTokenAuthenticator(context))
                .addInterceptor(loggingInterceptor)//third, log at the end
                .build();
于 2016-09-20T08:44:20.070 回答
5

我不知道 setLogLevel() 是否会在 Retrofit 的最终 2.0 版本中返回,但现在您可以使用拦截器进行日志记录。

OkHttp wiki 中有一个很好的例子:https ://github.com/square/okhttp/wiki/Interceptors

OkHttpClient client = new OkHttpClient();
client.interceptors().add(new LoggingInterceptor());

Retrofit retrofit = new Retrofit.Builder()
        .baseUrl("http://www.yourjsonapi.com")
        .addConverterFactory(GsonConverterFactory.create())
        .client(client)
        .build();
于 2015-09-16T00:29:20.890 回答
4

对于那些需要在 Retrofit 中进行高级日志记录的人,可以像这样使用拦截器

public static class LoggingInterceptor implements Interceptor {
    @Override public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        long t1 = System.nanoTime();
        String requestLog = String.format("Sending request %s on %s%n%s",
                request.url(), chain.connection(), request.headers());
        //YLog.d(String.format("Sending request %s on %s%n%s",
        //        request.url(), chain.connection(), request.headers()));
        if(request.method().compareToIgnoreCase("post")==0){
            requestLog ="\n"+requestLog+"\n"+bodyToString(request);
        }
        Log.d("TAG","request"+"\n"+requestLog);

        Response response = chain.proceed(request);
        long t2 = System.nanoTime();

        String responseLog = String.format("Received response for %s in %.1fms%n%s",
                response.request().url(), (t2 - t1) / 1e6d, response.headers());

        String bodyString = response.body().string();

        Log.d("TAG","response"+"\n"+responseLog+"\n"+bodyString);

        return response.newBuilder()
                .body(ResponseBody.create(response.body().contentType(), bodyString))
                .build();
        //return response;
    }
}

public 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";
    }
}`

礼貌https ://github.com/square/retrofit/issues/1072#

于 2015-09-30T05:16:11.463 回答
4

Kotlin 代码

        val interceptor = HttpLoggingInterceptor()
        interceptor.level = HttpLoggingInterceptor.Level.BODY
        val client = OkHttpClient.Builder().addInterceptor(interceptor).build()
        val retrofit = Retrofit.Builder()
                .baseUrl(BASE_URL)
                .client(client)
                .addConverterFactory(GsonConverterFactory.create())
                .build()

        return retrofit.create(PointApi::class.java)
于 2018-08-28T19:13:02.353 回答
4

以下代码集对我来说没有任何问题

摇篮

// Retrofit
implementation 'com.squareup.retrofit2:retrofit:2.5.0'
implementation 'com.squareup.retrofit2:converter-gson:2.5.0'
implementation 'com.squareup.okhttp3:logging-interceptor:3.12.1'

改造客户端

HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.BODY);

OkHttpClient client = new OkHttpClient.Builder()
        .addInterceptor(logging)
        .build();

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

您还可以通过进入 Android Studio 底部的 Profiler 选项卡来验证结果,然后单击 + 号以启动新会话,然后在“网络”中选择所需的峰值。在那里你可以得到一切,但它既麻烦又慢。请看下图。

在此处输入图像描述

于 2019-12-25T01:23:57.793 回答
2

您还可以添加 Facebook 的 Stetho,并在 Chrome 中查看网络跟踪:http: //facebook.github.io/stetho/

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

然后在 Chrome 中打开“chrome://inspect”...

于 2016-07-20T19:26:57.620 回答
2

对于 Retrofit 2.0.2,代码就像

   **HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
        logging.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient.Builder httpClient=new OkHttpClient.Builder();
        httpClient.addInterceptor(logging);**


        if (retrofit == null) {
            retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    **.client(httpClient.build())**
                    .build();
        }
于 2017-11-13T07:48:29.133 回答
2

这将创建一个带有 Logging 的改造对象。无需创建单独的对象。

 private static final Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(BASE_URL)
            .client(new OkHttpClient().newBuilder()
                    .addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
                    .readTimeout(READ_TIMEOUT_SECONDS, TimeUnit.SECONDS)
                    .writeTimeout(WRITE_TIMEOUT_SECONDS, TimeUnit.SECONDS)
                    .connectTimeout(CONNECTION_TIMEOUT_SECONDS, TimeUnit.SECONDS)
                    .build())
            .addConverterFactory(GsonConverterFactory.create())
            .build();
于 2018-12-13T05:38:38.683 回答
2

首先向 build.gradle 添加依赖:

实现 'com.squareup.okhttp3:logging-interceptor:3.12.1'

在使用 Kotlin 时,您可以像这样添加 Logging Interceptor:

companion object {
    val okHttpClient = OkHttpClient().newBuilder()
            .addInterceptor(HttpLoggingInterceptor().apply {
                level = HttpLoggingInterceptor.Level.BODY
            })
            .build()


    fun getRetrofitInstance(): Retrofit {
        val retrofit = Retrofit.Builder()
                .client(okHttpClient)
                .baseUrl(ScanNShopConstants.BASE_URL)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .build()

        return retrofit
    }
}
于 2019-05-29T07:30:44.850 回答
1

在 Retrofit 2 中正确执行此操作的最佳方法是将记录器拦截器添加为 networkInterceptor,这将打印出网络标头和您的自定义标头。重要的是要记住拦截器作为堆栈工作,并确保在最后添加记录器。

OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.addInterceptor(new MyCustomInterceptor());
builder.connectTimeout(60, TimeUnit.SECONDS);
builder.readTimeout(60, TimeUnit.SECONDS);
builder.writeTimeout(60, TimeUnit.SECONDS);
// important line here
builder.addNetworkInterceptor(LoggerInterceptor());
于 2017-05-03T15:24:16.447 回答
1

这里的大部分答案几乎涵盖了除此工具之外的所有内容,这是查看日志的最酷方法之一。

它是Facebook 的 Stetho这是在google chrome上监控/记录应用程序网络流量的绝佳工具。你也可以Github 上找到。

在此处输入图像描述

于 2017-11-09T09:36:13.697 回答
1

这是一种使用以下方式从日志中过滤任何请求/响应参数的简单方法HttpLoggingInterceptor

// Request patterns to filter
private static final String[] REQUEST_PATTERNS = {
    "Content-Type",
};
// Response patterns to filter
private static final String[] RESPONSE_PATTERNS = {"Server", "server", "X-Powered-By", "Set-Cookie", "Expires", "Cache-Control", "Pragma", "Content-Length", "access-control-allow-origin"};

// Log requests and response
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
    @Override
    public void log(String message) {

        // Blacklist the elements not required
        for (String pattern: REQUEST_PATTERNS) {
            if (message.startsWith(pattern)) {
                return;
            }
        }
        // Any response patterns as well...
        for (String pattern: RESPONSE_PATTERNS) {
            if (message.startsWith(pattern)) {
                return;
            }
        }
        Log.d("RETROFIT", message);
    }
});
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

这是完整的要点:

https://gist.github.com/mankum93/179c2d5378f27e95742c3f2434de7168

于 2019-08-15T17:04:02.660 回答
1

改造日志

Retrofit 的拦截器是一个很棒的功能,它允许你处理 http 请求。它们有两种类型:拦截器applicationnetwork

Charles Web Debugging Proxy Application如果您需要记录您的请求/响应,我建议您使用。输出非常相似,Stetho但它是更强大的工具,您不需要将其作为依赖项添加到应用程序

[Charles Proxy 变更响应]

于 2020-04-10T07:00:29.887 回答
0

我在改造中找到了打印日志的方法

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

为我工作。

于 2016-08-10T07:45:58.767 回答
0

java.lang.ClassNotFoundException用匕首的情况下

我删除了

implementation("com.squareup.okhttp3:okhttp:4.9.0")

一切正常。

于 2021-03-02T13:11:47.937 回答
-11

大家好,我已经找到解决方案了:

  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);
}
于 2015-09-11T06:43:26.513 回答