URLEncoder
should be the way to go. (URLEncoder
应该是要走的路。) You only need to keep in mind to encode only the individual query string parameter name and/or value, not the entire URL, for sure not the query string parameter separator character &
nor the parameter name-value separator character =
. (您只需要记住仅对单个查询字符串参数名称和/或值进行编码,而不对整个URL进行编码,请确保对查询字符串参数分隔符&
和参数名称-值分隔符=
不进行编码。)
String q = "random word £500 bank $";
String url = "http://example.com/query?q=" + URLEncoder.encode(q, "UTF-8");
Note that spaces in query parameters are represented by +
, not %20
, which is legitimately valid. (请注意,查询参数中的空格由+
表示,而不是%20
,这是合法有效的。) The %20
is usually to be used to represent spaces in URI itself (the part before the URI-query string separator character ?
), not in query string (the part after ?
). (%20
通常用于表示URI本身(URI查询字符串分隔符?
之前的部分)而不是查询字符串( ?
后面的部分)中的空格。)
Also note that there are two encode()
methods. (还要注意,有两种encode()
方法。) One without charset argument and another with. (一个不带charset参数,另一个不带charset参数。) The one without charset argument is deprecated. (不带charset参数的参数已弃用。) Never use it and always specify the charset argument. (从不使用它,并且始终指定charset参数。) The javadoc even explicitly recommends to use the UTF-8 encoding, as mandated by RFC3986 and W3C . (Javadoc甚至明确建议使用RFC3986和W3C要求的UTF-8编码。)
All other characters are unsafe and are first converted into one or more bytes using some encoding scheme. (所有其他字符都是不安全的,并且首先使用某种编码方案转换为一个或多个字节。) Then each byte is represented by the 3-character string "%xy", where xy is the two-digit hexadecimal representation of the byte. (然后,每个字节由3个字符的字符串“%xy”表示,其中xy是该字节的两位十六进制表示形式。) The recommended encoding scheme to use is UTF-8 . (推荐使用的编码方案是UTF-8 。) However, for compatibility reasons, if an encoding is not specified, then the default encoding of the platform is used. (但是,出于兼容性原因,如果未指定编码,则使用平台的默认编码。)
See also: (也可以看看:)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…