Get raw HTTP response with Retrofit

前端 未结 3 1597
有刺的猬
有刺的猬 2020-12-01 06:15

I want to get the raw http response from my API REST. I have tried with this interface:

@POST(\"/login\")
@FormUrlEncoded
Call login         


        
3条回答
  •  无人及你
    2020-12-01 06:47

    You can get information about headers, response code, down to raw json response body by using Interceptors. You can write your custom Interceptors but I prefer to use Square's own Logging Interceptor. It's available on maven central.

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

    Here's how to use it

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

    Logging level BODY will print headers to the body response. And in your Retrofit

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

    Now, open up Log Cat and you'll see raw HTTP response.

    Caution!

    Don't forget to remove Interceptors (or change Logging Level to NONE) in production! Otherwise people will be able to see your request and response on Log Cat.

提交回复
热议问题