要在j2me编程环境中提交utf-8编码方式的url请求,比如如下的URL中searchName是utf-8格式字节流
*)对于非utf-8格式的中文字符串,需要以下两个步骤:
1、获取utf-8编码流
byte[] bytes = null;
try {
bytes = name.getBytes("UTF-8");
} catch (UnsupportedEncodingException ex) {
ex.printStackTrace();
}
2、调用如下方法进行URL格式编码
public static String urlEncode(byte[] b)
{
final String hexChars="0123456789ABCDEF";//hex symbols
StringBuffer sb=new StringBuffer();
for(int i=0;i<b.length;i++)
{
sb.append('%');
sb.append(hexChars.charAt((b[i]&0xf0)>>4));
sb.append(hexChars.charAt(b[i]&0x0f));
}
return sb.toString();
}
String commentQueryUrl = "http://test.mygoogle.at/WebYee/servlet/WebContent?address=44&searchName="
+ urlEncode(bytes)
+ "&tel=55053838&type=44";
*)对于utf-8字符串,则简单一点,调用如下函数进行转换,然后填到相应的URL中:
public static String urlEncode(String str) {
StringBuffer buf = new StringBuffer();
byte[] bytes = null;
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(bos);
dos.writeUTF(str);
bytes = bos.toByteArray();
} catch (IOException e) {
// ignore
}
for (int i = 2; i < bytes.length; i++) {
byte b = bytes[i];
if (Consts.URL_UNRESERVED.indexOf(b) >= 0) {
buf.append((char) b);
} else {
buf.append('%').append(Consts.HEX[(b >> 4) & 0x0f]).append(Consts.HEX[b & 0x0f]);
}
}
return buf.toString();
}
如果不进行转换,也许在模拟器上可以正常获取到kml格式数据返回,但是在手机上却返回html访问错误信息。
如果你使用的kxml解析器,那么会抛出unexpected StartTag <html>这样的异常。