0
我們正在從Apache的http客戶端遷移到Retrofit,並且發現一些邊緣情況下參數值可能爲空。如何在Retrofit中處理空參數值
Apache用於攔截這些並將它們變成空字符串,但Retrofit會拋出IllegalArgumentException。
我們想要複製舊的行爲,以便它不會在生產中引發任何意外問題。有沒有辦法讓我在ParameterHandler引發異常之前將這些空值與空字符串交換?
我們正在從Apache的http客戶端遷移到Retrofit,並且發現一些邊緣情況下參數值可能爲空。如何在Retrofit中處理空參數值
Apache用於攔截這些並將它們變成空字符串,但Retrofit會拋出IllegalArgumentException。
我們想要複製舊的行爲,以便它不會在生產中引發任何意外問題。有沒有辦法讓我在ParameterHandler引發異常之前將這些空值與空字符串交換?
你可以嘗試以下方法:
我的web服務(Asp.Net的WebAPI):
[Route("api/values/getoptional")]
public IHttpActionResult GetOptional(string id = null)
{
var response = new
{
Code = 200,
Message = id != null ? id : "Response Message"
};
return Ok(response);
}
Android客戶端:
public interface WebAPIService {
...
@GET("/api/values/getoptional")
Call<JsonObject> getOptional(@Query("id") String id);
}
MainActivity.java:
...
Call<JsonObject> jsonObjectCall1 = service.getOptional("240780"); // or service.getOptional(null);
jsonObjectCall1.enqueue(new Callback<JsonObject>() {
@Override
public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
Log.i(LOG_TAG, response.body().toString());
}
@Override
public void onFailure(Call<JsonObject> call, Throwable t) {
Log.e(LOG_TAG, t.toString());
}
});
...
logcat的輸出:
如果使用service.getOptional(null);
04-15 13:56:56.173 13484-13484/com.example.asyncretrofit I/AsyncRetrofit: {"Code":200,"Message":"Response Message"}
如果使用service.getOptional("240780");
04-15 13:57:56.378 13484-13484/com.example.asyncretrofit I/AsyncRetrofit: {"Code":200,"Message":"240780"}