J2ME UTF-8编码 URL请求

要在j2me编程环境中提交utf-8编码方式的url请求,比如如下的URL中searchName是utf-8格式字节流

http://test.mygoogle.at/WebYee/servlet/WebContent?address=44&searchName=%E4%B8%8A%E6%B5%B7%E6%96%B0%E4%B8%96%E7%95%8C%E4%B8%BD%E7%AC%99%E5%A4%A7%E9%85%92%E5%BA%97&tel=55053838&type=44

 

*)对于非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        {
            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 这样的异常。

你可能感兴趣的:(J2ME)