我没有在android studio中获取请求和响应请求的日志。 我什至在Retrofit2中使用HttpLogginInterceptor。但是我无法在Logcat中看到请求正文和响应正文的日志。
这里有我的改造客户:
import java.util.concurrent.TimeUnit;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class RestClient {
private static RestClient restClient;
private Retrofit retrofitAuth;
private Retrofit retrofit;
/**
* only to be used for auth
*/
public static WebServices webServices() {
return getRestClient().getRetrofitInstance().create(WebServices.class);
}
public static WebServices webAuthServices() {
return getRestClient().getAuthRetrofitInstance().create(WebServices.class);
}
private static RestClient getRestClient() {
if (restClient == null) {
restClient = new RestClient();
}
return restClient;
}
private Retrofit getRetrofitInstance() {
if (retrofit == null) {
retrofit = new Retrofit.Builder()
.baseUrl(BuildConfig.API_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(getOkHttpClient())
.build();
}
return retrofit;
}
private Retrofit getAuthRetrofitInstance() {
if (retrofitAuth == null) {
retrofitAuth = new Retrofit.Builder()
.baseUrl(BuildConfig.API_URL)
.client(getAuthOkHttpClient())
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofitAuth;
}
private OkHttpClient getOkHttpClient() {
return new OkHttpClient.Builder()
.readTimeout(60, TimeUnit.SECONDS)
.connectTimeout(60, TimeUnit.SECONDS)
.addInterceptor(new ConnectivityInterceptor())
.addInterceptor(new HeaderAdder())
.addInterceptor(new AuthInterceptor())
.addInterceptor(getHttpLoggingInterceptor())
.build();
}
private OkHttpClient getAuthOkHttpClient() {
return new OkHttpClient.Builder()
.readTimeout(60, TimeUnit.SECONDS)
.connectTimeout(60, TimeUnit.SECONDS)
.addInterceptor(new HeaderAdder())
.addInterceptor(new ConnectivityInterceptor())
.addInterceptor(getHttpLoggingInterceptor())
.build();
}
private HttpLoggingInterceptor getHttpLoggingInterceptor() {
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
return logging;
}
public static void destroyRestClient() {
restClient = null;
}
}
如您所见,倒数第二个函数返回HttpLoggingInterceptor, 然后将其提供给okhttp客户端,然后将该客户端添加到改造实例中。但是我仍然看不到日志。请帮忙。
答案 0 :(得分:-1)
请将此库添加到Gradle文件中
// Retrofit-2
implementation 'com.squareup.okhttp3:logging-interceptor:3.9.1'
val interceptor = HttpLoggingInterceptor()
interceptor.level = HttpLoggingInterceptor.Level.BODY
val client = OkHttpClient.Builder()
.connectTimeout(30, TimeUnit.SECONDS)
.writeTimeout(30, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.addInterceptor(interceptor)
.build()
GlobalApp.api = Retrofit.Builder()
.baseUrl(END_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build().create(Api::class.java)