OGeek|极客世界-中国程序员成长平台

标题: android - Android 中的 URL 编码 [打印本页]

作者: 菜鸟教程小白    时间: 2022-8-1 01:19
标题: android - Android 中的 URL 编码

你如何编码 URL在安卓?

我以为是这样的:

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

如果我执行上述操作,http://urlAsString替换为 http%3A%2F%2FencodedURL然后我得到一个 java.net.MalformedURLException当我使用 URL 时。



Best Answer-推荐答案


您不会对整个 URL 进行编码,只对来自“不可靠来源”的部分进行编码。

  • 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"
    

  • 或者,您可以使用 Strings.urlEncode(String str)DroidParts不会抛出已检查的异常。
    或者使用类似的东西
    String uri = Uri.parse("http://...")
                    .buildUpon()
                    .appendQueryParameter("key", "val")
                    .build().toString();
    

    关于android - Android 中的 URL 编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3286067/






    欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://jike.in/) Powered by Discuz! X3.4