改造 2 - 空响应主体

Retrofit 2 - null response body

我正在尝试将以下响应转换为 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."
    ]
}

但我总是在 onResponse 方法中得到 null 响应。所以我试着用 response.errorBody.string() 查看响应的错误主体。错误正文包含与原始响应完全相同的内容。

这是我的服务方法,Retrofit 对象和响应数据 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);

我用 jsonschema2pojo 控制了响应 JSON,看看我是否对我的响应 class 进行了建模,看起来还不错。

为什么 Retrofit 无法转换我的响应?

更新

目前,作为解决方法,我正在构建错误正文的响应。

我已经解决了问题。当我发出错误请求 (HTTP 400) 时,Retrofit 不会转换响应。在这种情况下,您可以使用 response.errorBody.string() 访问原始响应。之后就可以新建一个Gson,手动转换:

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();
    }
}