Python:POST-using请求中的错误请求

2024-06-25 05:35:22 发布

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

我应该寄这个:

curl --header "Content-Type: text/plain" --request POST --data "ON" example.com/rest/items/z12

相反,我要发送这个:

import requests
headers = {"Content-Type": "text/plain"}
url = 'http://example.com/rest/items/z12'
_dict = {"ON": ""}
res = requests.post(url, auth=('demo', 'demo'), params=_dict, headers=headers)

我收到错误400(错误请求?)在

我做错什么了?在


Tags: textcomresturldemoonexampletype
2条回答

POST body被设置为ON;使用data参数:

import requests

headers = {"Content-Type": "text/plain"}
url = 'http://example.com/rest/items/z12'

res = requests.post(url, auth=('demo', 'demo'), data="ON", headers=headers)

params参数用于URL查询参数,通过使用字典,您要求{}将其编码为表单编码;因此,?ON=被添加到URL中。在

参见^{} manpage

(HTTP) Sends the specified data in a POST request to the HTTP server, in the same way that a browser does when a user has filled in an HTML form and presses the submit button.

以及^{} API

data – (optional) Dictionary, bytes, or file-like object to send in the body of the Request.

requests.post方法中的params参数用于向URL添加GET参数。所以你在做这样的事情:

curl  header "Content-Type: text/plain"  request POST example.com/rest/items/z12?ON=

您应该改为使用data参数。在

^{pr2}$

此外,如果给data参数一个字典,它将以“application/x-www-form-urlencoded”的形式发送有效负载。在curl命令中,发送原始字符串作为有效负载。所以我改变了你的例子。在

相关问题 更多 >