Java URL编码的查询字符串参数 [英] Java URL encoding of query string parameters

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

问题描述

说我有一个URL

  http://example.com/query?q= 

,我有一个用户输入的查询,例如:


随机字£500银行$


我希望结果是一个正确编码的URL:

  http://example.com/query?q=random%20word%20%A3500%20bank%20%24 

实现此目的最好的方法是什么?我尝试了 URLEncoder 并创建URI / URL对象,但没有一个出来很正确。

解决方案

URLEncoder 应该是走的路。您只需要记住,仅单独的查询字符串参数名称和/或值,而不是整个URL,以确定不是查询字符串参数分隔符字符& 或参数名称值分隔符字符 =

  String q =随机字£500银行$; 
String url =http://example.com/query?q=+ URLEncoder.encode(q,UTF-8);






请注意,查询参数中的空格用 + ,而不是%20 ,这是合法有效的。 %20 通常用于表示URI本身的空格(URI查询字符串分隔符之前的部分),而不是查询字符串(之后的部分?)。



另请注意, code> encode()方法。一个没有charset的参数和另一个。没有charset参数的一个被弃用。不要使用它,并始终指定charset参数。 javadoc 甚至明确建议使用UTF -8编码,如 RFC3986 W3C


所有其他字符都不安全,首先使用一些编码方案将其转换成一个或多个字节。然后每个字节由3个字符的字符串%xy表示,其中xy是字节的两位十六进制表示。 使用的推荐编码方案是UTF-8 。但是,出于兼容性原因,如果未指定编码,则使用平台的默认编码。




另请参见: / h3>


Say I have a URL

http://example.com/query?q=

and I have a query entered by the user such as:

random word £500 bank $

I want the result to be a properly encoded URL:

http://example.com/query?q=random%20word%20%A3500%20bank%20%24

What's the best way to achieve this? I tried URLEncoder and creating URI/URL objects but none of them come out quite right.

解决方案

URLEncoder should be the way to go. 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 =.

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. 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 ?).

Also note that there are two encode() methods. One without charset argument and another with. The one without charset argument is deprecated. Never use it and always specify the charset argument. The javadoc even explicitly recommends to use the UTF-8 encoding, as mandated by RFC3986 and W3C.

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. The recommended encoding scheme to use is UTF-8. However, for compatibility reasons, if an encoding is not specified, then the default encoding of the platform is used.

See also:

这篇关于Java URL编码的查询字符串参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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