如何将字符串转换为unicode / utf以传入URL?

时间:2017-01-13 14:04:09

标签: android url unicode encode

我的字符串是:

ĐT70, Châu Linh, Tùng Ảnh, Đức Thọ, Hà Tĩnh, Vietnam.

在url查询字符串中传递此文本时,它将显示为:

ĐT70%2C+Châu+Linh%2C+Tùng+Ảnh%2C+Đức+Thọ%2C+Hà+Tĩnh%2C+Vietnam.

但我想用这种格式:

\U0111\U01b0\U1eddng \U0110\U1eadp, Th\U00f4ng T\U1ef1, T\U00f9ng \U1ea2nh, \U0110\U1ee9c Th\U1ecd, H\U00e0 T\U0129nh, Vietnam.

我怎么能以这种格式获得该字符串?请回答。

1 个答案:

答案 0 :(得分:2)

经过努力终于找到了解决方案。

 //String that you want to convert
  String mystring = "133 Phùng Hưng, Cửa Đông, Hoàn Kiếm, Hà Nội, Vietnam";

    //unicodeString is the expected output in unicode 
    String unicodeString = getUnicodeString(escapeUnicodeText(mystring));

   //i want to make small u into Capital from unicode String
  String resultUnicode = unicodeString.replace("\\u", "\\U");

    try {
        String text = URLEncoder.encode(mystring, "UTF-8");
        Log.v("currentDateTimeString", "text String:" + text);
    } catch (Exception e) {
        e.printStackTrace();
    }

创建方法escapeUnicodeText以将Unicode文本转换为unicode fromat,例如,如果在escapeUnicodeText()中传递输入字符串♫you,您将获得unicode输出,如\ u266b \ u00e9

public String escapeUnicodeText(String input) {

    StringBuilder b = new StringBuilder(input.length());

    java.util.Formatter f = new java.util.Formatter(b);

    for (char c : input.toCharArray()) {
        if (c < 128) {
            b.append(c);
        } else {
            f.format("\\u%04x", (int) c);
        }
    }

    return b.toString();
}

将escapeUnicodeText的输出传递到getUnicodeString(),你会得到你的预期结果,如\ U0111 \ U01b0 \ U1eddng \ U0110 \ U1eadp,Th \ U00f4ng T \ U1ef1,T \ U00f9ng \ U1ea2nh,\ U0110 \ U1ee9c Th \ U1ecd, H \ U00e0 T \ U0129nh,越南。

 public String getUnicodeString(String myString) {
    String text = "";
    try {

         byte[] utf8Bytes = myString.getBytes("UTF8");
        text = new String(utf8Bytes, "UTF8");

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    return text;
}