310

我在网上找到了这个脚本:

import httplib, urllib
params = urllib.urlencode({'number': 12524, 'type': 'issue', 'action': 'show'})
headers = {"Content-type": "application/x-www-form-urlencoded",
            "Accept": "text/plain"}
conn = httplib.HTTPConnection("bugs.python.org")
conn.request("POST", "", params, headers)
response = conn.getresponse()
print response.status, response.reason
302 Found
data = response.read()
data
'Redirecting to <a href="http://bugs.python.org/issue12524">http://bugs.python.org/issue12524</a>'
conn.close()

但我不明白如何将它与 PHP 一起使用,或者 params 变量中的所有内容是什么,或者如何使用它。我可以在尝试使其正常工作方面提供一些帮助吗?

4

7 回答 7

462

如果你真的想使用 Python 处理 HTTP,我强烈推荐Requests: HTTP for Humans。适合您的问题的 POST 快速入门是:

>>> import requests
>>> r = requests.post("http://bugs.python.org", data={'number': 12524, 'type': 'issue', 'action': 'show'})
>>> print(r.status_code, r.reason)
200 OK
>>> print(r.text[:300] + '...')

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>
Issue 12524: change httplib docs POST example - Python tracker

</title>
<link rel="shortcut i...
>>> 
于 2012-07-04T08:08:46.227 回答
176

这是一个没有任何外部 pip 依赖项的解决方案,但仅适用于 Python 3+(Python 2 不起作用):

from urllib.parse import urlencode
from urllib.request import Request, urlopen

url = 'https://httpbin.org/post' # Set destination URL here
post_fields = {'foo': 'bar'}     # Set POST fields here

request = Request(url, urlencode(post_fields).encode())
json = urlopen(request).read().decode()
print(json)

样本输出:

{
  "args": {}, 
  "data": "", 
  "files": {}, 
  "form": {
    "foo": "bar"
  }, 
  "headers": {
    "Accept-Encoding": "identity", 
    "Content-Length": "7", 
    "Content-Type": "application/x-www-form-urlencoded", 
    "Host": "httpbin.org", 
    "User-Agent": "Python-urllib/3.3"
  }, 
  "json": null, 
  "origin": "127.0.0.1", 
  "url": "https://httpbin.org/post"
}
于 2016-04-17T15:30:20.670 回答
35

您无法使用urllib(仅适用于 GET)实现 POST 请求,而是尝试使用requests模块,例如:

示例 1.0:

import requests

base_url="www.server.com"
final_url="/{0}/friendly/{1}/url".format(base_url,any_value_here)

payload = {'number': 2, 'value': 1}
response = requests.post(final_url, data=payload)

print(response.text) #TEXT/HTML
print(response.status_code, response.reason) #HTTP

示例 1.2:

>>> import requests

>>> payload = {'key1': 'value1', 'key2': 'value2'}

>>> r = requests.post("http://httpbin.org/post", data=payload)
>>> print(r.text)
{
  ...
  "form": {
    "key2": "value2",
    "key1": "value1"
  },
  ...
}

示例 1.3:

>>> import json

>>> url = 'https://api.github.com/some/endpoint'
>>> payload = {'some': 'data'}

>>> r = requests.post(url, data=json.dumps(payload))
于 2016-04-10T07:49:17.983 回答
18

通过点击 REST API 端点,使用requests库来 GET、POST、PUT 或 DELETE。将其余 api 端点 url 传入url,payload(dict) indata和 header/metadata inheaders

import requests, json

url = "bugs.python.org"

payload = {"number": 12524, 
           "type": "issue", 
           "action": "show"}

header = {"Content-type": "application/x-www-form-urlencoded",
          "Accept": "text/plain"} 

response_decoded_json = requests.post(url, data=payload, headers=header)
response_json = response_decoded_json.json()
 
print(response_json)
于 2018-12-05T08:38:38.450 回答
6

您的数据字典包含表单输入字段的名称,您只需保持正确的值即可查找结果。 表单视图 标题配置浏览器以检索您声明的数据类型。使用 requests 库很容易发送 POST:

import requests

url = "https://bugs.python.org"
data = {'@number': 12524, '@type': 'issue', '@action': 'show'}
headers = {"Content-type": "application/x-www-form-urlencoded", "Accept":"text/plain"}
response = requests.post(url, data=data, headers=headers)

print(response.text)

有关请求对象的更多信息:https ://requests.readthedocs.io/en/master/api/

于 2020-01-20T14:28:08.710 回答
2

如果您不想使用必须安装的模块requests,并且您的用例非常基本,那么您可以使用urllib2

urllib2.urlopen(url, body)

请参阅urllib2此处的文档:https ://docs.python.org/2/library/urllib2.html 。

于 2019-01-17T20:17:48.497 回答
0

您可以使用请求库来发出发布请求。如果负载中有 JSON 字符串,则可以使用 json.dumps(payload) ,这是负载的预期形式。


    import requests, json
    url = "http://bugs.python.org/test"
    payload={
        "data1":1234,'data2':'test'
    }
    headers = {
        'Content-Type': 'application/json'
    }
    response = requests.post(url, headers=headers, data=json.dumps(payload))
    print(response.text , response.status_code)

于 2021-09-10T02:38:16.473 回答