如何发送POST请求?

时间:2012-07-04 04:30:03

标签: python urllib httplib

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

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变量中的所有内容或者如何使用它。我可以请一点帮助试图让它发挥作用吗?

5 个答案:

答案 0 :(得分:321)

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

>>> 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...
>>> 

答案 1 :(得分:125)

如果你需要你的脚本是可移植的,而你宁愿没有任何第三方依赖,那么这就是你在Python 3中发送POST请求的方式。

ViewModel

示例输出:

[HttpPost]
public ActionResult Edit(OrderArchiveViewModel model)

答案 2 :(得分:32)

您无法使用urllib实现POST请求(仅限GET),而是尝试使用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))

答案 3 :(得分:4)

通过点击REST API端点,使用requests库进行GET,POST,PUT或DELETE。在url中传递其余api端点URL,在data中传递有效负载(dict),并在headers中传递标头/元数据

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=head)
 response_json = response_decoded_json.json()

 print response_json

答案 4 :(得分:1)

如果您不想使用类似requests的模块,并且用例非常基础,那么可以使用urllib2

urllib2.urlopen(url, body)

在此处查看urllib2的文档:https://docs.python.org/2/library/urllib2.html