如何使用Retrofit 2.0获得原始响应和请求 [英] How to get raw response and request using Retrofit 2.0

查看:152
本文介绍了如何使用Retrofit 2.0获得原始响应和请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Retrofit2.0.2获得原始响应.

I am trying to get the raw response using Retrofit2.0.2.

到目前为止,我尝试使用下面的代码行打印响应,但它打印的是地址而不是确切的响应正文.

So far I tried to print the response using following line of code but it prints the address and not the exact response body.

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);

                }
            });

推荐答案

那是因为它已经被转换器转换为对象.要获取原始json,您需要在Http Client上使用拦截器.幸运的是,您不需要编写自己的类,Square已经为您提供了HttpLoggingInterceptor类.

That's because it's already converted to an object by converter. To get the raw json, you need an interceptor on your Http Client. Thankfully you don't need to write your own class, Square already provide HttpLoggingInterceptor class for you.

将此添加到您的应用级gradle中

Add this on your app-level gradle

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

并在您的OkHttpClient中使用它

And use it in your OkHttpClient

HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder()
                .addInterceptor(interceptor).build();

别忘了在翻新中更改您的HttpClient.

Don't forget to change your HttpClient in Retrofit.

Retrofit retrofit = new Retrofit.Builder()
            .client(client)               
            .baseUrl("https://yourapi.com/api/")
            .build();

在Log Cat中,您将看到原始的json响应.有关更多信息,请参见Square的 OkHttp github .

In the Log Cat you'll see the raw json response. Further information is available on Square's OkHttp github.

警告!

不要忘记在生产中删除拦截器(或将日志记录级别"更改为无")!否则,人们将能够在Log Cat上看到您的请求和响应.

这篇关于如何使用Retrofit 2.0获得原始响应和请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆