我试图使用Retrofit2.0.2获得原始响应.
到目前为止,我尝试使用以下代码行打印响应,但它打印的是地址而不是确切的响应正文.
Log.i(“RAW MESSAGE”,response.body().toString());
编译’com.squareup.retrofit2:retrofit:2.0.2′
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
GitApi gitApi = retrofit.create(GitApi.class);
Call<Addresses> call = gitApi.getFeed(user);
call.enqueue(new Callback<Addresses>() {
@Override
public void onResponse(Response<Addresses> response, Retrofit retrofit) {
try {
mDisplayDetails.setText(response.body().getSuburbs().get(0).getText());
**Log.i("RAW MESSAGE",response.body().toString());**
} catch (Exception e) {
mDisplayDetails.setText(e.getMessage());
}
mProgressBar.setVisibility(View.INVISIBLE);
}
@Override
public void onFailure(Throwable t) {
mDisplayDetails.setText(t.getMessage());
mProgressBar.setVisibility(View.INVISIBLE);
}
});
解决方法:
那是因为它已经通过转换器转换为对象.要获取原始json,您需要在Http客户端上使用拦截器.值得庆幸的是,你不需要编写自己的类,Square已经为你提供了HttpLoggingInterceptor类.
在您的应用级gradle上添加此项
compile 'com.squareup.okhttp3:logging-interceptor:3.5.0'
并在你的OkHttpClient中使用它
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(interceptor).build();
不要忘记在Retrofit中更改您的HttpClient.
Retrofit retrofit = new Retrofit.Builder()
.client(client)
.baseUrl("https://yourapi.com/api/")
.build();
在Log Cat中,您将看到原始json响应.更多信息可在Square的OkHttp github上获得.
警告!
不要忘记在生产中删除拦截器(或将记录级别更改为NONE)!否则,人们将能够在Log Cat上看到您的请求和响应.