在Android的URL编码Android、URL

2023-09-12 21:29:06 作者:瘠薄梦!

你怎么连接codeA 网址在Android的?

How do you encode a URL in Android?

我以为是这样的:

final String encodedURL = URLEncoder.encode(urlAsString, "UTF-8");
URL url = new URL(encodedURL);

如果我做了上述情况,的http:// urlAsString 替换 HTTP%3A%2F%2F 连接codedURL ,然后我得到一个 java.net.MalformedURLException 当我使用的URL。

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.

推荐答案

您没有连接$ C C完整的URL $,只有来自可靠来源它的一部分。

You don't encode the entire URL, only parts of it that come from "unreliable sources".

String query = URLEncoder.encode("apples oranges", "utf-8");
String url = "http://stackoverflow.com/search?q=" + query;

另外,你可以使用Strings.urlEn$c$c(String STR)的 DroidParts 不抛出checked异常。

Alternatively, you can use Strings.urlEncode(String str) of DroidParts that doesn't throw checked exceptions.

或者使用类似

String uri = Uri.parse("http://...")
                .buildUpon()
                .appendQueryParameter("key", "val")
                .build().toString();