Android - How to Convert String to utf-8 in android

前端 未结 4 803
陌清茗
陌清茗 2020-12-17 21:14

I can\'t convert a String to UTF-8 in android. please help me!!

s1=URLEncoder.encode(\"臺北市\")

result : %EF%BF%BDO%EF%BF%BD_%EF%BF%BD%

相关标签:
4条回答
  • 2020-12-17 21:27

    use this:

            URLEncoder.encode("臺北市", "UTF-8");
    
    0 讨论(0)
  • 2020-12-17 21:28
    public class StringFormatter {
    
        // convert UTF-8 to internal Java String format
        public static String convertUTF8ToString(String s) {
            String out = null;
            try {
                out = new String(s.getBytes("ISO-8859-1"), "UTF-8");
            } catch (java.io.UnsupportedEncodingException e) {
                return null;
            }
            return out;
        }
    
        // convert internal Java String format to UTF-8
        public static String convertStringToUTF8(String s) {
            String out = null;
            try {
                out = new String(s.getBytes("UTF-8"), "ISO-8859-1");
            } catch (java.io.UnsupportedEncodingException e) {
                return null;
            }
            return out;
        }
    
    }
    

    You can convert your string using StringFormatter class to your code.

    You want to convert to UTF-8:

    String normal="This normal string".
    String utf=StringFormatter.convertStringToUTF8(normal);
    

    You want to convert UTF-8 to normal format:

    String normal=StringFormatter.convertUTF8ToString(normal);
    
    0 讨论(0)
  • 2020-12-17 21:32

    You can just use,

    URLEncoder.encode(string, "UTF-8");
    

    This will encode your "string: in UTF-8 format.

    Put it in a try/catch and check for IllegalArgumentException if you want to. And if you have any spaces in your string, please replace it with

    string.replace(" ", "%20");
    
    0 讨论(0)
  • 2020-12-17 21:39

    In http://developer.android.com/reference/java/net/URLEncoder.html you can read that the you used is deprecated and that you should use static String encode(String s, String charsetName)

    So URLEncoder.encode("臺北市", "utf-8") should do the trick.

    0 讨论(0)
提交回复
热议问题