How to handle null param values in Retrofit

有些话、适合烂在心里 提交于 2019-12-12 01:38:16

问题


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, but Retrofit throws an IllegalArgumentException.

We want to replicate the old behavior so that it doesn't cause any unexpected issues out in production. Is there a way for me to swap these null values with empty strings before ParameterHandler throws an exception?


回答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:

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 output:

If using service.getOptional(null);

04-15 13:56:56.173 13484-13484/com.example.asyncretrofit I/AsyncRetrofit: {"Code":200,"Message":"Response Message"}

If using service.getOptional("240780");

04-15 13:57:56.378 13484-13484/com.example.asyncretrofit I/AsyncRetrofit: {"Code":200,"Message":"240780"}


来源:https://stackoverflow.com/questions/36634926/how-to-handle-null-param-values-in-retrofit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!