如何在HTTP POST / GET中发送空参数

时间:2018-08-21 11:42:21

标签: java android http okhttp3

在http发表/获取请求中发送空值的正确方法是什么。

重要提示:我的意思是为请求的特定参数发送 NULL 值,而不是空字符串或缺少字段。 我认为以下选项不正确

http://test.com?param1=&param2=bar      //this is an empty string, not a null
http://test.com?param1=null&param2=bar  //this is a string with content "null"
http://test.com?param2=bar              //param 1 is missing, not null

在HTTP中发送 NULL 是否有意义(已标准化),还是应该回退到以前的任何选项?在后一种情况下,标准方法是什么

在使用Java的情况下:

URLEncoder.encode(null, "UTF-8")

它以Attempt to invoke virtual method 'int java.lang.String.length()' on a null object reference

崩溃

使用 OkHttp3 lib并尝试添加空参数时,我也会崩溃

FormBody.Builder bodyBuilder = new FormBody.Builder();
bodyBuilder.add("param1",null)

2 个答案:

答案 0 :(得分:1)

如果您要在此处添加null参数,请仅使用空白的""字符串代替null参数,这将显示异常,因为它找到了发送HTTP请求的null值

答案 1 :(得分:1)

您在问题中没有取消资格的唯一明智选择是没有值的参数。

http://example.com?param1&param2&param3=foo

尽管我会完全不将属性添加到查询字符串中,因为它会导致值“没有值”,这通常是null的意思。

相关问题