URL中的转义与号

2024-04-24 11:01:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试发送一个GET消息,该消息包含带与号的字符串,并且不知道如何在URL中转义与号。

示例:

http://www.example.com?candy_name=M&M
result => candy_name = M

我也试过:

http://www.example.com?candy_name=M\&M
result => candy_name = M\\

我是手动使用网址,所以我只需要正确的字符。

我不能用任何图书馆。怎么能做到?


Tags: 字符串namecomhttp消息url示例get
3条回答

这不仅适用于url中的与号,而且适用于所有reserved characters。其中包括:

 # $ & + ,  / : ; = ? @ [ ]

其思想与在HTML文档中对&进行编码相同,但除了在HTML文档中之外,上下文也已更改为在URI中。因此,百分比编码防止了在两个上下文中解析的问题。

当你需要将一个URL放在另一个URL中时,这个方法就非常有用了。例如,如果要在Twitter上发布状态:

http://www.twitter.com/intent/tweet?status=What%27s%20up%2C%20StackOverflow%3F(http%3A%2F%2Fwww.stackoverflow.com)

我的Tweet中有很多保留字符,即?'():/,因此我对statusURL参数的整个值进行了编码。这在使用具有消息正文或主题的mailto:链接时也很有用,因为您需要对bodysubject参数进行编码,以保持换行符、与号等的完整性。

When a character from the reserved set (a "reserved character") has special meaning (a "reserved purpose") in a certain context, and a URI scheme says that it is necessary to use that character for some other purpose, then the character must be percent-encoded. Percent-encoding a reserved character involves converting the character to its corresponding byte value in ASCII and then representing that value as a pair of hexadecimal digits. The digits, preceded by a percent sign ("%") which is used as an escape character, are then used in the URI in place of the reserved character. (For a non-ASCII character, it is typically converted to its byte sequence in UTF-8, and then each byte value is represented as above.) The reserved character "/", for example, if used in the "path" component of a URI, has the special meaning of being a delimiter between path segments. If, according to a given URI scheme, "/" needs to be in a path segment, then the three characters "%2F" or "%2f" must be used in the segment instead of a raw "/".

http://en.wikipedia.org/wiki/Percent-encoding#Percent-encoding_reserved_characters

它们需要百分比编码:

> encodeURIComponent('&')
"%26"

所以在你的例子中,URL看起来像:

http://www.mysite.com?candy_name=M%26M

尝试使用http://www.example.org?candy_name=M%26M

另请参见this reference和一些详细信息on Wikipedia

相关问题 更多 >