The +
字符是引用 GET 或 POST 数据时空格的正确编码。因此,字面上的+
字符也需要转义,以免被解码为另一端的空格。参见 RFC 2396,第2.2节 https://www.rfc-editor.org/rfc/rfc2396#section-2.2, 第3.4节 https://www.rfc-editor.org/rfc/rfc2396#section-3.4和HTML 规范,application/x-www-form-urlencoded section http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.1:
控件名称和值被转义。空格字符被替换为“+”,然后保留字符被转义,如[RFC1738] http://www.w3.org/TR/html401/references.html#ref-RFC1738,第 2.2 节。
如果您将数据发布到不解码的应用程序+
字符转换为空格,而是将此类数据视为文字加号,您需要使用以下方式自己对参数进行编码urllib.quote功能 http://docs.python.org/library/urllib.html#urllib.quote相反,指定+
字符不被编码:
import urllib
def urlencode_withoutplus(query):
if hasattr(query, 'items'):
query = query.items()
l = []
for k, v in query:
k = urllib.quote(str(k), safe=' /+')
v = urllib.quote(str(v), safe=' /+')
l.append(k + '=' + v)
return '&'.join(l)
Demo:
>>> urlencode_withoutplus({'arg0': 'value', 'arg1': '+value'})
'arg0=value&arg1=+value'
使用时requests
,您可以简单地将上述函数的结果作为data
值,但在这种情况下您需要手动设置内容类型:
requests.post(url, urlencode_withoutplus(query),
headers={'Content-Type': 'application/x-www-form-urlencoded'})