簡體   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