I want to get the raw http response from my API REST. I have tried with this interface:
@POST(\"/login\")
@FormUrlEncoded
Call login
To get access to the raw response, use ResponseBody
from okhttp as your call type.
Call<ResponseBody> login(...)
In your callback, you can check the response code with the code
method of the response. This applies to any retrofit 2 return type, because your callback always gets a Response
parameterized with your actual return type. For asynchronous --
Call<ResponseBody> myCall = myApi.login(...)
myCall.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Response<ResponseBody> response, Retrofit retrofit) {
// access response code with response.code()
// access string of the response with response.body().string()
}
@Override
public void onFailure(Throwable t) {
t.printStackTrace();
}
});
for synchronous calls --
Response<ResponseBody> response = myCall.execute();
System.out.println("response code" + response.code());
I had the same problem but a different solution. I took the request and send it with OkHttp3Client. Like this:
//raw text
Request request = call.clone().request();
OkHttpClient client = new OkHttpClient();
okhttp3.Response test = client.newCall(request).execute();
System.out.println(test.body().string());
source: http://robinhenniges.com/de/retrofit-2-raw-response
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.