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<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>这样的异常。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值