在为GET请求编码参数时如何处理空字符串?

时间:2012-08-22 11:50:17

标签: string java-me char urlencode

我正在研究一个使用HTTP GET请求与服务器通信的J2ME应用程序。我已经有了生成URL编码参数的方法。

在目前的形式中,无法迎合空字符串,我见过的其他代码片段也存在这种缺陷,因为它们都依赖于比较字符串参数的各个字符。{ {3}}

修改

对服务器(Play 1.0)的请求采用

格式

I have previously asked a question related to this empty char dilemma

参数不能为空,因此http:server.com/setname/firstname//lastname无效

从json对象中检索参数。目前我所拥有的url编码方法将正确编码所有提取的参数,并保留任何无法转换为的字符。字符串中的空格,如“Jo e”和空格字符本身将分别编码为Jo%20e和%20。 JSON对象

{ "firstname":"joe"
  "othername":""
  "lastname":"bloggs"
}  
但是,

会导致无效的网址http://server.com/setName/firstname/othername/lastname,因为othername参数是一个空字符串,并且由我的方法保留。

我可以检查要返回的字符串是否为空并返回空格字符。但是我想知道是否对这种方法没有更好的修改,或者是一种更健壮的全新方法?

 public static String urlEncode(String s) {
    ByteArrayOutputStream bOut = null;
    DataOutputStream dOut = null;
    ByteArrayInputStream bIn = null;
    StringBuffer ret = new StringBuffer();
    try {
        bOut=new ByteArrayOutputStream();
        dOut = new DataOutputStream(bOut);
        //return value
        dOut.writeUTF(s);
        bIn = new ByteArrayInputStream(bOut.toByteArray());
        bIn.read();
        bIn.read();
        int c = bIn.read();
        while (c >= 0) {
            if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '.' || c == '-' || c == '*' || c == '_') {
                ret.append((char) c);
            } else if (c == ' ' ) {
                //ret.append('+');
                ret.append("%20");
            } else {
                if (c < 128) {
                    appendHex(c, ret);
                } else if (c < 224) {
                    appendHex(c, ret);
                    appendHex(bIn.read(), ret);
                } else if (c < 240) {
                    appendHex(c, ret);
                    appendHex(bIn.read(), ret);
                    appendHex(bIn.read(), ret);
                }
            }
            c = bIn.read();
        }
    } catch (IOException ioe) {
        System.out.println("urlEncode:"+ioe);
        return s;
    }
       return ret.toString();
}

private static void appendHex(int arg0, StringBuffer buff) {
    buff.append('%');
    if (arg0 < 16) {
        buff.append('0');
    }
    buff.append(Integer.toHexString(arg0));
}

1 个答案:

答案 0 :(得分:4)

根据RFC 1738,没有空字符的URL编码。这为您提供了四个选项。

  1. 要求填充所有字段。这可能不是一个好的选择,具体取决于您的应用程序的功能,因为用户可能没有特定字段的数据,或者不想共享它。

  2. 如果只有一个字段可以允许为空,请重新排序URL参数,使其成为最后一个。这将产生/joe/bloggs/而不是/joe//bloggs

  3. 如果某个网址可能包含多个空参数,则最好使用查询字符串。这看起来像/setName?firstname=joe&othername=&lastname=bloggs。未使用的参数可以省略或包含在内。

  4. 使用POST而不是GET。只需使用网址/setName并将所有字段放入表单即可。根据URL,显然正在执行的操作似乎更适合POST而不是GET。