pra*_*mar 17 java android retrofit okhttp retrofit2
我试图使用Retrofit2.0.2获得原始响应.
到目前为止,我尝试使用以下代码行打印响应,但它打印的地址而不是确切的响应正文.
Log.i("RAW MESSAGE",response.body().toString());
compile '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);
}
});
Run Code Online (Sandbox Code Playgroud)
那是因为它已经通过转换器转换为对象.要获取原始json,您需要在Http客户端上使用拦截器.值得庆幸的是,你不需要编写自己的类,Square已经为你提供了HttpLoggingInterceptor类.
在您的应用级gradle上添加此项
compile 'com.squareup.okhttp3:logging-interceptor:3.5.0'
Run Code Online (Sandbox Code Playgroud)
并在你的OkHttpClient中使用它
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(interceptor).build();
Run Code Online (Sandbox Code Playgroud)
不要忘记在Retrofit中更改您的HttpClient.
Retrofit retrofit = new Retrofit.Builder()
.client(client)
.baseUrl("https://yourapi.com/api/")
.build();
Run Code Online (Sandbox Code Playgroud)
在Log Cat中,您将看到原始json响应.有关Square的OkHttp github的更多信息.
警告!
不要忘记在生产中删除拦截器(或将记录级别更改为NONE)!否则,人们将能够在Log Cat上看到您的请求和响应.
只需使用:
Log.i("RAW MESSAGE", response.raw().body().string());
Run Code Online (Sandbox Code Playgroud)
或者:
Log.i("RAW MESSAGE", response.body().string());
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12846 次 |
| 最近记录: |