Android中的URL编码 [英] URL encoding in Android

查看:95
本文介绍了Android中的URL编码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您如何在 Android 中对 URL 进行编码?

How do you encode a URL in Android?

我以为是这样的:

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

如果我这样做了,urlAsString中的http://中的http%3A%2F%2F替换>encodedURL 然后我在使用 URL 时得到一个 java.net.MalformedURLException.

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.

推荐答案

您不会对整个 URL 进行编码,只会对其中来自不可靠来源"的部分进行编码.

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

  • Java:

  • Java:

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

  • 科特林:

  • Kotlin:

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

  • 或者,您可以使用 字符串DroidParts 的 .urlEncode(String str) 不会抛出已检查的异常.

    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();
    

    这篇关于Android中的URL编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆