[英]Retrofit 2 - Response body null when response status is 422 (unprocessable entity)
我正在使用 Retrofit 在我的 Web 服務器中發出 POST 請求。
但是,當響應狀態為422 (unprocessable entity)
時,我似乎無法獲取響應正文。 響應正文始終為null
。
我想知道我是否做錯了什么,或者是否有解決方法。 因為我在Postman的請求中使用了相同的 json,它正常返回正文。
這是方法:
@Headers("Content-Type: application/vnd.api+json")
@POST("my_endpoint")
Call<JsonObject> postEntry(@Header("Authorization") String authorization, @Body JsonObject json);
主體是一個 JsonObject,我沒有像文檔所說的那樣進行序列化。 但我不認為這是問題所在。
默認情況下,當您的服務器返回錯誤代碼response.body()
始終為null
。 您正在尋找的是response.errorBody()
。 一種常見的方法是這樣的:
@Override
public void onResponse(Response<JsonObject> response, Retrofit retrofit) {
if (response.isSuccess()) {
response.body(); // do something with this
} else {
response.errorBody(); // do something with that
}
}
我得到了同樣的錯誤。 我的 API 使用 POSTMAN 請求工作,但無法通過 Android 改造調用工作。
起初我嘗試使用 @Field 但它出錯了,但后來我嘗試使用 @Body 並且它起作用了。
示例 Retrofit 接口調用
@POST("api/v1/app/instance")
Call<InstanceResponse> updateTokenValue(
@HeaderMap Map<String, String> headers,
@Body String body);
和API調用代碼是:
Map<String, String> headerMap=new HashMap<>();
headerMap.put("Accept", "application/json");
headerMap.put("Content-Type", "application/json");
headerMap.put("X-Authorization","access_token");
Map<String, String> fields = new HashMap<>();
fields.put("app_name", "video");
fields.put("app_version", "2.0.0");
fields.put("firebase_token", "token");
fields.put("primary", "1");
ApiInterface apiInterface = ApiClient.getApiClient().create(ApiInterface.class);
Call<InstanceResponse> call = apiInterface.updateTokenValue(
headerMap,new Gson().toJson(fields));
那么在這種情況下,您必須轉換響應。 看看這個鏈接
所有步驟都已在上面的鏈接中提供。
對於 Kotlin 用戶,這里是代碼解決方案。
ErrorResponse.kt (這顯然取決於您的錯誤響應)
import com.squareup.moshi.Json
data class ErrorResponse(
@Json(name="name")
val name: String? = null,
@Json(name="message")
val message: String? = null,
@Json(name="errors")
val errors: Errors? = null,
@Json(name="statusCode")
val statusCode: Int? = null
)
ApiFactory.kt (如果您需要完整代碼,請告訴我)
fun parseError(response: Response<*>): ErrorResponse {
val converter = ApiFactory.retrofit()
.responseBodyConverter<ErrorResponse>(
ErrorResponse::class.java, arrayOfNulls<Annotation>(0)
)
val error: ErrorResponse
try {
error = converter.convert(response.errorBody()!!)!!
} catch (e: IOException) {
e.printStackTrace()
return ErrorResponse()
}
return error
}
並在演示者中(我使用 MVP)
GlobalScope.launch(Dispatchers.Main) {
try {
val response = ApiFactory.apiService.LOGIN(username, password)
.await()
val body = response.body()
body?.let {
// Handle success or any other stuff
if (it.statusCode == 200) {
mView.onSuccess(it.data!!)
}
} ?:
// This is the else part where your body is null
// Here is how you use it.
// Pass the response for error handling
mView.showMessage(ApiFactory.parseError(response).message!!)
} catch (e: Exception) {
e.printStackTrace()
}
}
這就是你如何滾動它! 這就是所有的人!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.