How To Handle Null Param Values In Retrofit
We're moving from Apache's http client to Retrofit and we've found some edge cases where param values can be null. Apache used to intercept these and turn them into empty strings,
Solution 1:
You can try the following:
My web service (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 client:
publicinterfaceWebAPIService{
...
@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(newCallback<JsonObject>() {
@OverridepublicvoidonResponse(Call<JsonObject> call, Response<JsonObject> response) {
Log.i(LOG_TAG, response.body().toString());
}
@OverridepublicvoidonFailure(Call<JsonObject> call, Throwable t) {
Log.e(LOG_TAG, t.toString());
}
});
...
Logcat output:
If using service.getOptional(null);
04-1513:56:56.17313484-13484/com.example.asyncretrofit I/AsyncRetrofit: {"Code":200,"Message":"Response Message"}
If using service.getOptional("240780");
04-1513:57:56.37813484-13484/com.example.asyncretrofit I/AsyncRetrofit: {"Code":200,"Message":"240780"}
Post a Comment for "How To Handle Null Param Values In Retrofit"