Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrofit 2 - null response body

I am trying to convert following response with Retrofit 2

{
    "errorNumber":4,
    "status":0,
    "message":"G\u00f6nderilen de\u011ferler kontrol edilmeli",
    "validate":[
        "Daha \u00f6nceden bu email ile kay\u0131t olunmu\u015f. L\u00fctfen giri\u015f yapmay\u0131 deneyiniz."
    ]
}

But I am allways getting null response in onResponse method. So I tried to look at error body of the response with response.errorBody.string(). Error body contains exactly same content with raw response.

Here is my service method, Retrofit object and response data declerations:

@FormUrlEncoded
@POST("/Register")
@Headers("Content-Type: application/x-www-form-urlencoded")
Call<RegisterResponse> register(
        @Field("fullName")  String fullName,
        @Field("email")     String email,
        @Field("password")  String password);

public class RegisterResponse {
    public int status;
    public String message;
    public int errorNumber;
    public List<String> validate;
}

OkHttpClient client = new OkHttpClient();
client.interceptors().add(new Interceptor() {
    @Override
    public Response intercept(Chain chain) throws IOException {
        Response response = chain.proceed(chain.request());
        final String content = UtilityMethods.convertResponseToString(response);
        Log.d(TAG, lastCalledMethodName + " - " + content);
        return response.newBuilder().body(ResponseBody.create(response.body().contentType(), content)).build();
    }
});
Retrofit retrofit = new Retrofit.Builder()
        .baseUrl(BASE_URL)
        .addConverterFactory(GsonConverterFactory.create())
        .client(client)
        .build();
domainSearchWebServices = retrofit.create(DomainSearchWebServices.class);

I have controlled response JSON with jsonschema2pojo to see if I modled my response class wright and it seems OK.

Why Retrofit fails to convert my response?

UPDATE

For now as a work around I am building my response from error body.

like image 459
Olcay Ertaş Avatar asked Nov 17 '15 13:11

Olcay Ertaş


1 Answers

I have solved the problem. When I make a bad request (HTTP 400) Retrofit doesn't convert the response. In this case you can access the raw response with response.errorBody.string(). After that you can create a new Gson and convert it manually:

if (response.code() == 400 ) {
    Log.d(TAG, "onResponse - Status : " + response.code());
    Gson gson = new Gson();
    TypeAdapter<RegisterResponse> adapter = gson.getAdapter(RegisterResponse.class);
    try {
        if (response.errorBody() != null)
            registerResponse = 
                adapter.fromJson(
                    response.errorBody().string());
    } catch (IOException e) {
        e.printStackTrace();
    }
}
like image 69
Olcay Ertaş Avatar answered Nov 17 '22 23:11

Olcay Ertaş