简体   繁体   English

如何使用Retrofit 2.0获得原始响应和请求

[英]How to get raw response and request using Retrofit 2.0

I am trying to get the raw response using Retrofit2.0.2. 我试图使用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()); 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);

                }
            });

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. 要获取原始json,您需要在Http客户端上使用拦截器。 Thankfully you don't need to write your own class, Square already provide HttpLoggingInterceptor class for you. 值得庆幸的是,你不需要编写自己的类,Square已经为你提供了HttpLoggingInterceptor类。

Add this on your app-level gradle 在您的应用级gradle上添加此项

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

And use it in your OkHttpClient 并在你的OkHttpClient中使用它

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

Don't forget to change your HttpClient in Retrofit. 不要忘记在Retrofit中更改您的HttpClient。

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

In the Log Cat you'll see the raw json response. 在Log Cat中,您将看到原始json响应。 Further information is available on Square's OkHttp github . 有关Square的OkHttp github的更多信息。

Caution! 警告!

Don't forget to remove Interceptors (or change Logging Level to NONE) in production! 不要忘记在生产中删除拦截器(或将记录级别更改为NONE)! Otherwise people will be able to see your request and response on Log Cat. 否则,人们将能够在Log Cat上看到您的请求和响应。

Simply use: 只需使用:

Log.i("RAW MESSAGE", response.raw().body().string());

Or: 要么:

Log.i("RAW MESSAGE", response.body().string());

You have to use "ResponseBody" from okhttp3 in your call. 您必须在通话中使用okhttp3中的“ResponseBody”。 Then, get "response.body().string()" to get the JSONObject as your server gives to you. 然后,获取“response.body()。string()”以获取服务器提供给您的JSONObject。 It's a good way to catch errors if there are any errors parsing server response to your model object. 如果解析服务器对模型对象的响应有任何错误,这是捕获错误的好方法。

Guess you want to see the raw response body for debugging purpose. 猜猜你想看到原始响应体以进行调试。 There are two ways to do this. 有两种方法可以做到这一点。

  1. Using okhttp3.logging.HttpLoggingInterceptor as @aldok mentioned. 使用okhttp3.logging.HttpLoggingInterceptor作为@aldok提到。

  2. If you want to check some properties of the response object, or convert the json(response body) to POJO manually, you may want to do it like this: 如果要检查响应对象的某些属性,或者手动将json(响应体)转换为POJO,您可能希望这样做:

Don't use the addConverterFactory while initializing the retrofit client, comment this line. 初始化改造客户端时不要使用addConverterFactory,请注释此行。

retrofit = new Retrofit.Builder()
                .client(client)
                .baseUrl(BASE_URL)
                //.addConverterFactory(GsonConverterFactory.create())
                .build();

Then consuming the response like this: 然后消耗这样的响应:

Call<ResponseBody> topRatedResponseCall = apiService.getTopRatedMoves(API_KEY);
    topRatedResponseCall.enqueue(new Callback<ResponseBody>() {
        @Override
        public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
            try {
                Log.d(LOG_TAG, response.body().string());
                int code = response.code();
                testText.setText(response.body().string());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onFailure(Call<ResponseBody> call, Throwable t) {

        }
    });

Hope this would help~ 希望这会有所帮助〜

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM