Android中的UTF-8转换?

Pra*_*een 5 java string android utf-8

我遇到了一个需要调用Web服务的问题.我只需要生成一个UTF-8编码的url字符串.因为参数可能包含空格,我使用下面的代码编码为utf-8:

public String encodeUTF(String str) {

        try {
            byte[] utf8Bytes = str.getBytes("UTF-8");

            String encodedStr = new String(utf8Bytes, "UTF-8");

            return encodedStr;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return str;
    }
Run Code Online (Sandbox Code Playgroud)

但我仍然得到相同的价值.因此,我在调用服务时遇到非法参数异常.有任何想法吗?

fra*_*yab 11

对于UTF编码,请使用此 - > URLEncoder.encode(string, "UTF-8");

你还需要改变空格 - > string.replace(" ", "%20");


Par*_*ani 6

就试一试吧:

URLEncoder.encode(str, "UTF-8");
Run Code Online (Sandbox Code Playgroud)