【发布时间】:2012-08-17 20:05:59
【问题描述】:
我正在开发一个使用 HTTP GET 请求与服务器通信的 J2ME 应用程序。我已经有了生成 URL 编码参数的方法。
在目前的形式中,它不能处理空字符串,我见过的其他代码 sn-ps 也有这个缺陷,因为它们都依赖于比较字符串参数的各个字符.I have previously asked a question related to this empty char dilemma
编辑:
对服务器的请求(Play 1.0)的格式为
http://server.com/setName/firstname/othername/lastname
参数不能为空,所以 http:server.com/setname/firstname//lastname 无效
参数是从 json 对象中检索的。目前我拥有的 url 编码方法将正确编码所有提取的参数,并保留任何无法按原样转换的字符。字符串中的空格,如“Jo e”和空格字符本身将分别编码为 Jo%20e 和 %20。 JSON 对象
{ "firstname":"joe"
"othername":""
"lastname":"bloggs"
}
但是会导致无效的 url http://server.com/setname/joe//bloggs,因为 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));
}
【问题讨论】:
-
“但是它不能/不能满足空字符串” - 究竟是什么意思?空字符串究竟在哪里引起了问题,那是什么问题?是否有异常/崩溃,或者您只是得到意外/不希望的行为?
-
所有参数都需要吗?是否有一个可选参数,或者可以有多个?
标签: string java-me char urlencode