且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从Python发送HTTP POST请求(尝试从PHP转换)

更新时间:2022-06-01 05:20:05

你太过复杂了。 Python会为您处理大部分内容。无需自己打开套接字,也不需要构建标头和HTTP开头行。

You are overcomplicating things, by quite some distance. Python takes care of most of this for you. There is no need to open a socket yourself, nor do you need to build headers and the HTTP opening line.

使用 urllib urllib2 模块为您完成工作:

Use the urllib and urllib2 modules to do the work for you:

from urllib import urlencode
from urllib2 import urlopen

params = urlencode(postfields)
url = whmcsurl + 'modules/servers/licensing/verify.php'
response = urlopen(url, params)
data = response.read()

urlopen()接受第二个参数,即要在 POST 请求中发送的数据;该库负责计算主体的长度,并设置适当的标题。最重要的是,它使用另一个库, httplib ,负责处理套接字连接并生成有效的标头和HTTP请求行。

urlopen() takes a second parameter, the data to be sent in a POST request; the library takes care of calculating the length of the body, and sets the appropriate headers. Most of all, under the hood it uses another library, httplib, to take care of the socket connection and producing valid headers and a HTTP request line.

POST主体使用 urllib进行编码.urlencode(),它也会为您正确报价。

The POST body is encoded using urllib.urlencode(), which also takes care of proper quoting for you.

您可能还想查看外部请求,它提供了一个更易于使用的API:

You may also want to look into the external requests library, which provides an easier-to-use API still:

import requests

response = requests.post(whmcsurl + 'modules/servers/licensing/verify.php', params=params)
data = response.content  # or response.text for decoded content, or response.json(), etc.