Android中的URL编码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3286067/
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
URL encoding in Android
提问by hpique
How do you encode a URLin Android?
你如何在 Android 中对URL进行编码?
I thought it was like this:
我以为是这样的:
final String encodedURL = URLEncoder.encode(urlAsString, "UTF-8");
URL url = new URL(encodedURL);
If I do the above, the http://
in urlAsString
is replaced by http%3A%2F%2F
in encodedURL
and then I get a java.net.MalformedURLException
when I use the URL.
如果我执行上述操作,则http://
inurlAsString
将被http%3A%2F%2F
in替换encodedURL
,然后java.net.MalformedURLException
在使用 URL 时得到 a 。
回答by yanchenko
You don't encode the entire URL, only parts of it that come from "unreliable sources".
您不会对整个 URL 进行编码,只对来自“不可靠来源”的部分进行编码。
String query = URLEncoder.encode("apples oranges", "utf-8");
String url = "http://stackoverflow.com/search?q=" + query;
Alternatively, you can use Strings.urlEncode(String str)of DroidPartsthat doesn't throw checked exceptions.
或者,您可以使用不会抛出已检查异常的DroidParts 的Strings.urlEncode(String str)。
Or use something like
或者使用类似的东西
String uri = Uri.parse("http://...")
.buildUpon()
.appendQueryParameter("key", "val")
.build().toString();
回答by Craig B
I'm going to add one suggestion here. You can do this which avoids having to get any external libraries.
我要在这里添加一个建议。您可以这样做,以避免必须获得任何外部库。
Give this a try:
试试这个:
String urlStr = "http://abc.dev.domain.com/0007AC/ads/800x480 15sec h.264.mp4";
URL url = new URL(urlStr);
URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(), url.getQuery(), url.getRef());
url = uri.toURL();
You can see that in this particular URL, I need to have those spaces encoded so that I can use it for a request.
您可以看到在这个特定的 URL 中,我需要对这些空格进行编码,以便我可以将其用于请求。
This takes advantage of a couple features available to you in Android classes. First, the URL class can break a url into its proper components so there is no need for you to do any string search/replace work. Secondly, this approach takes advantage of the URI class feature of properly escaping components when you construct a URI via components rather than from a single string.
这利用了 Android 类中可用的几个功能。首先,URL 类可以将 url 分解为其适当的组件,因此您无需进行任何字符串搜索/替换工作。其次,当您通过组件而不是从单个字符串构造 URI 时,这种方法利用了正确转义组件的 URI 类特性。
The beauty of this approach is that you can take any valid url string and have it work without needing any special knowledge of it yourself.
这种方法的美妙之处在于您可以使用任何有效的 url 字符串并使其工作,而无需您自己对此有任何特殊知识。
回答by tanutapi
For android, I would use String android.net.Uri.encode(String s)
对于 android,我会使用 String android.net.Uri.encode(String s)
Encodes characters in the given string as '%'-escaped octets using the UTF-8 scheme. Leaves letters ("A-Z", "a-z"), numbers ("0-9"), and unreserved characters ("_-!.~'()*") intact. Encodes all other characters.
使用 UTF-8 方案将给定字符串中的字符编码为 '%' 转义八位字节。保持字母(“AZ”、“az”)、数字(“0-9”)和非保留字符(“_-!.~'()*”)不变。编码所有其他字符。
Ex/
前任/
String urlEncoded = "http://stackoverflow.com/search?q=" + Uri.encode(query);
回答by Jedo
Also you can use this
你也可以用这个
private static final String ALLOWED_URI_CHARS = "@#&=*+-_.,:!?()/~'%";
String urlEncoded = Uri.encode(path, ALLOWED_URI_CHARS);
it's the most simple method
这是最简单的方法
回答by Joolah
try {
query = URLEncoder.encode(query, "utf-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
回答by Elango
you can use below methods
您可以使用以下方法
public static String parseUrl(String surl) throws Exception
{
URL u = new URL(surl);
return new URI(u.getProtocol(), u.getAuthority(), u.getPath(), u.getQuery(), u.getRef()).toString();
}
or
或者
public String parseURL(String url, Map<String, String> params)
{
Builder builder = Uri.parse(url).buildUpon();
for (String key : params.keySet())
{
builder.appendQueryParameter(key, params.get(key));
}
return builder.build().toString();
}
the second one is better than first.
第二个比第一个好。
回答by Ali Jafari
Find Arabic chars and replace them with its UTF-8 encoding. some thing like this:
查找阿拉伯字符并将其替换为其 UTF-8 编码。像这样的事情:
for (int i = 0; i < urlAsString.length(); i++) {
if (urlAsString.charAt(i) > 255) {
urlAsString = urlAsString.substring(0, i) + URLEncoder.encode(urlAsString.charAt(i)+"", "UTF-8") + urlAsString.substring(i+1);
}
}
encodedURL = urlAsString;