如何在改造中处理空参数值 [英] How to handle null param values in Retrofit

查看:50
本文介绍了如何在改造中处理空参数值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们正在从 Apache 的 http 客户端迁移到 Retrofit,我们发现了一些参数值可以为 null 的边缘情况.

We're moving from Apache's http client to Retrofit and we've found some edge cases where param values can be null.

Apache 过去会拦截这些并将它们转换为空字符串,但 Retrofit 会抛出 IllegalArgumentException.

Apache used to intercept these and turn them into empty strings, but Retrofit throws an IllegalArgumentException.

我们希望复制旧行为,以便它不会在生产中导致任何意外问题.在 ParameterHandler 抛出异常之前,有没有办法让我用空字符串交换这些空值?

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?

推荐答案

您可以尝试以下操作:

我的网络服务 (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:

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"}

这篇关于如何在改造中处理空参数值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆