使用Python中的请求生成HTTP POST请求

2024-04-26 07:13:42 发布

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

我正在尝试使用POST方法向API发出HTTP请求。我正在使用的API打算接受三个参数(key1、key2、key3)并返回一个json文件。不幸的是,当我使用data方法将字典传递给API时,POST请求似乎没有返回任何内容。这似乎很奇怪,因为当我使用params方法时,它似乎起作用。我无法理解这一点,因为这个过程看起来非常不透明(例如,我无法通过URL来查看负载是如何传递到API的)。

我的问题:我在这里做错了什么?

使用data方法将参数发送到API的POST请求:

import requests

url = 'http://example.com/API.php'
payload =  {
            'key1': '<<Contains very long json string>>', 
            'key2': 5, 
            'key3': 0
           }

print len(str(payload)) # Prints 6717
r = requests.post(url, data=payload) << Note data is used here
print r.status_code # Prints 200
print r.text # Prints empty string

使用params方法将参数发送到API的请求后代码:

import requests

url = 'http://example.com/API.php'
payload =  {
            'key1': '<<Contains very long json string>>', 
            'key2': 5, 
            'key3': 0
           }

print len(str(payload)) # Prints 6717
r = requests.post(url, params=payload) << Note here params is used here
print r.status_code # Prints 200
print r.text # Prints expected JSON results

如果您想知道我为什么要使用data方法而不是params。。。我正试图传递其他包含较长字符串的字典,而params方法似乎没有做到这一点,因为我得到了错误414。我希望通过使用数据可以解决这个错误。

我使用的API是用PHP编写的。


Tags: 方法apijsonurldata参数paramsprints
1条回答
网友
1楼 · 发布于 2024-04-26 07:13:42

简短回答
这是因为params作为http POST请求的一部分发送参数,而数据作为请求主体的一部分发送参数。在您的例子中:只要使用params调用api就可以了。这绝对是正常的(和预期的)行为。

演示
开始两条命令。首先,运行netcat:nc -l 8888。在另一条命令行上,运行python:

>>> import requests
>>> requests.post('http://localhost:8888',data={'a':1,'b':'2'})

在netcat端,我们看到以下请求:

POST / HTTP/1.1
Host: localhost:8888
Connection: keep-alive
Accept-Encoding: gzip, deflate
Accept: */*
User-Agent: python-requests/2.18.1
Content-Length: 7
Content-Type: application/x-www-form-urlencoded

a=1&b=2

接下来,尝试params方式:

>>> requests.post('http://localhost:8888',params={'a':1,'b':'2'})

Netcat报告:

POST /?a=1&b=2 HTTP/1.1
Host: localhost:8888
Connection: keep-alive
Accept-Encoding: gzip, deflate
Accept: */*
User-Agent: python-requests/2.18.1
Content-Length: 0

注意第一行和最后一行的区别。

你可以从documentation(斜体强调是我的):

params -- (optional) Dictionary or bytes to be sent in the query string for the Request.
data -- (optional) Dictionary or list of tuples [(key, value)] (will be form-encoded), bytes, or file-like object to send in the body of the Request.

相关问题 更多 >