Retrofit 2 - null response body

后端 未结 1 1884
终归单人心
终归单人心 2020-12-08 21:44

I am trying to convert following response with Retrofit 2

{
    \"errorNumber\":4,
    \"status\":0,
    \"message\":\"G\\u00f6nderilen de\\u011         


        
相关标签:
1条回答
  • 2020-12-08 22:11

    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();
        }
    }
    
    0 讨论(0)
提交回复
热议问题