我应该为每个 URL 参数使用 URLEncoder

Should I use URLEncoder for each URL parametr

对于我的 android 应用程序中的每个服务器请求,我都需要对参数进行编码,因此 URL 的字符串看起来像

"http://example.com/script.php?param1="+URLEncoder.encode(param1.getText().toString(), "UTF-8")+"param2="+URLEncoder.encode(param2.getText().toString(), "UTF-8")+...."

它有效,但也许 URLEncoder.encode 只能使用一次 - 就像这样

URLEncoder.encode("http://example.com/script.php?param1="+param1.getText().toString()+"param2="+param2.getText().toString()+....", "UTF-8")

是否可以,或者在某些情况下会崩溃?

URL 编码整个 URL 将不起作用,因为它会导致类似

的结果
"http%3A%2F%2Fexample.com%2Fscript.php%3Fparam1%3Dasdf%26param2%3Djkl"

即整个 URL 中的所有特殊字符都将被编码。您也不能 url 对整个查询字符串进行编码,因为 = 和 & 字符将被编码。

您必须对每个参数值进行编码,以阻止参数中的特殊字符干扰 URL 解析。辅助功能可以减轻疼痛。

String url = "http://example.com/script.php?" + encodeArgs("a", "a + b", "b", "=xxx=");

以及一些让你入门的东西

public String encodeArgs(String... args) {
    final String encoding = "UTF-8";
    try {
        if (args.length % 2 != 0) {
            throw new IllegalArgumentException("number of arguments not even");
        }

        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < args.length; i += 2) {
            sb.append(URLEncoder.encode(args[i], encoding));
            sb.append("=");
            sb.append(URLEncoder.encode(args[i + 1], encoding));
            sb.append("&");
        }

        // delete last &, if any
        if (sb.length() > 0) {
            sb.deleteCharAt(sb.length() - 1);
        }

        return sb.toString();

    } catch (UnsupportedEncodingException e) {
        throw new IllegalArgumentException("unsupported encoding " + encoding, e);
    }
}

你不应该编码完整 URL。仅对参数部分进行编码,换句话说,仅对来自 "unreliable sources".

的部分进行编码

所以你的第一次尝试 "http://example.com/script.php?param1="+URLEncoder.encode(param1.getText().toString(), "UTF-8")+"param2="+URLEncoder.encode(param2.getText().toString(), "UTF-8")+...." 是正确的,你应该继续。


URL encoding in Android and Android: howto parse URL String with spaces to URI object? 可能有助于提高清晰度。