Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get raw HTTP response with Retrofit

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

@POST("/login") @FormUrlEncoded Call<retrofit.Response> login(@Field("username") String login, @Field("password") String pass,                      @Field("appName") String appName, @Field("appKey") String appKey); 

But I get:

java.lang.IllegalArgumentException: Unable to create call adapter for retrofit.Call for method Api.login

I create Retrofit this way:

Retrofit.Builder retrofitBuilder = new Retrofit.Builder(); retrofitBuilder.addConverterFactory(JacksonConverterFactory.create()); Retrofit retrofitAdapter = retrofitBuilder.baseUrl(baseUrl).build(); return retrofitAdapter.create(apiClass); 
like image 222
Héctor Avatar asked Oct 22 '15 13:10

Héctor


People also ask

How do you post raw whole JSON in the body of a retrofit request?

The Best Answer is The @Body annotation defines a single request body. Since Retrofit uses Gson by default, the FooRequest instances will be serialized as JSON as the sole body of the request. The Gson docs have much more on how object serialization works. And then use an instance of that class similar to #1.

How do you pass body in GET request retrofit on Android?

This means your @GET or @DELETE should not have @Body parameter. You can use query type url or path type url or Query Map to fulfill your need. Else you can use other method annotation.


1 Answers

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()); 
like image 149
iagreen Avatar answered Sep 21 '22 02:09

iagreen