无法在 HttpLoggingInterceptor Retrofit 2.0 上解析 setLevel

Cant resolve setLevel on HttpLoggingInterceptor Retrofit2.0

我正在使用 Retrofit,我想记录我的响应和其他事情,我正在使用这种 https://futurestud.io/tutorials/retrofit-2-log-requests-and-responses 类型,但我面临 无法解析 setLevel 错误

HttpLoggingInterceptor logging = new HttpLoggingInterceptor();  

logging.setLevel(Level.BODY); // i am getting error on this

OkHttpClient.Builder httpClient = new OkHttpClient.Builder();  

httpClient.addInterceptor(logging); //this is also getting error

我正在用这个 编译'com.squareup.okhttp3:logging-interceptor:3.3.1'并改造 编译'com.squareup.retrofit2:converter-gson:2.1.0'依赖。

getClient() 方法中编写您的 interceptor 代码,例如

public class RestClient {

    public getClient() {

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

将此依赖项添加到您应用的 gradle:

 compile 'com.squareup.okhttp3:logging-interceptor:3.2.0'

并像下面这样使用它: 像下面这样构建你的 OkHttpClient

final OkHttpClient.Builder okHttpClientBuilder = new OkHttpClient.Builder();
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
okHttpClientBuilder.addInterceptor(interceptor);
okHttpClientBuilder.connectTimeout(RestConstants.DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS)
return okHttpClientBuilder.build();

并将其设置为您的 Retrofit 作为客户端。

我建议您检查您的应用是否 Debuggable 然后设置您的日志拦截器。所以在生产中你不会记录 api 结果。

你可以这样做,我的问题解决了:-

        HttpLoggingInterceptor logg = new HttpLoggingInterceptor();
        logg.setLevel(HttpLoggingInterceptor.Level.BODY);
        httpClient = new OkHttpClient.Builder();
        httpClient.addInterceptor(logg);
define following plugins of retrofit in build.gradle(Mobile:app) correctly as show below...

dependencies {
 ..........
   implementation('com.squareup.retrofit2:retrofit:2.3.0')
            {
                exclude module: 'okhttp'
            }
    implementation 'com.squareup.retrofit2:converter-gson:2.3.0'
    implementation 'com.squareup.okhttp3:logging-interceptor:3.9.1'
}

Works For Sure....@Ambilpura Sunil

如果您使用的是 okhttp3,请确保导入 okhttp3(而不是 okhttp)日志记录:

改变

implementation 'com.squareup.okhttp:logging-interceptor:3.14.1'

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

https://whosebug.com/users/5316836/pitty 回答得很好 只是想提供更多代码来解释如何 link 使用 Retrofit.Builder

的答案
public class RestClient {
    public OkHttpClient getClient() {
        HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
        logging.setLevel(HttpLoggingInterceptor.Level.BODY);

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


        return client;
    }
}

RestClient rc = new RestClient();

private NetworkService() {
    mRetrofit = new Retrofit.Builder()
            .baseUrl(BASE_URL)
            .client(rc.getClient())
            .addConverterFactory(GsonConverterFactory.create())
            .build();

}