java Android中的UTF-8转换?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7845998/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
UTF-8 conversion in Android?
提问by Praveen
I am encountering a problem that I need to call a web service. I just need to generate a UTF-8 encoded url string. Because the parameter may contain spaces, I am using below piece of code to encode to 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;
}
But still I am getting the same value. Because of this I am getting illegal argument exception while calling the service. Any ideas?
但我仍然得到相同的价值。因此,我在调用服务时收到非法参数异常。有任何想法吗?
回答by frayab
For UTF encoding use this -> URLEncoder.encode(string, "UTF-8");
对于 UTF 编码,使用这个 -> URLEncoder.encode(string, "UTF-8");
Also you need to change spaces -> string.replace(" ", "%20");
您还需要更改空格-> string.replace(" ", "%20");
回答by Paresh Mayani
Just try it:
去尝试一下:
URLEncoder.encode(str, "UTF-8");
回答by Ricardo Centeno Lugo
You can use this:
你可以使用这个:
import java.net.URLEncoder;
class{
String TEXT;
TEXT= URLEncoder.encode(TEXT, "UTF-8");
}