繁体   English   中英

改造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响应,看我是否模拟了我的响应类wright,看起来没问题。

为什么Retrofit无法转换我的回复?

UPDATE

现在作为一个解决方案,我正在构建我的错误正文的响应。

我已经解决了这个问题。 当我提出错误请求(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();
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM