我试图让我的网络类记录传入的JSON,我想使用OkHttp3中的HttpLoggingInterceptor。问题是我的Retrofit对象不会从okhttp3获取OkHttpClient。如果你知道我做错了什么,请告诉我。
摇篮
compile 'com.squareup.retrofit:retrofit:2.0.0-beta4'
compile 'com.squareup.okhttp3:okhttp:3.1.2'
compile 'com.squareup.retrofit:converter-jackson:2.0.0-beta2'
compile 'com.squareup.okhttp3:logging-interceptor:3.0.1'
改造和客户端设置
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit.Retrofit;
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
client = new OkHttpClient.Builder().addInterceptor(interceptor).build();
retrofit = new Retrofit.Builder().baseUrl(URL).client(client).addConverterFactory(JacksonConverterFactory.create()).build();
API = retrofit.create(com.glasshouse.glasshouse.Network.API.class);
Android工作室说Retrofit需要okhttp.OkHttpClient而不是okhttp3.OkHttpClient但是如果使用那个,我就不能使用HttpLoggingInterceptor ......
感谢您的回答。
答案 0 :(得分:1)
是的,没关系 - 对于那些面临类似问题的人,请使用retrofit2而不是改装
(需要导入retrofit2.Retrofit not import retrofit.Retrofit)
答案 1 :(得分:1)
作为其他人的参考,你需要在你的gradle中编译“com.squareup.retrofit2”而不是“com.squareup.retrofit”。
//old
compile 'com.squareup.retrofit:retrofit:2.0.0-beta4'
//new
compile 'com.squareup.retrofit2:retrofit:2.0.0-beta4'
答案 2 :(得分:0)
我正在使用以下配置进行改造,效果很好。
内部build.gradle:
compile 'com.squareup.okhttp3:okhttp:3.0.1'
compile 'com.squareup.okhttp:logging-interceptor:2.6.0'
compile 'com.fasterxml.jackson.core:jackson-core:2.4.1'
compile 'com.fasterxml.jackson.core:jackson-annotations:2.4.1'
compile 'com.fasterxml.jackson.core:jackson-databind:2.4.1'
改装配置:
private WebServices getWebServices(String serverUrl) {
OkHttpClient client = new OkHttpClient();
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
client.interceptors().add(interceptor);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(serverUrl)
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build();
webServices = retrofit.create(WebServices.class);
return webServices;
}