首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何发送POST请求?

如何发送POST请求?
EN

Stack Overflow用户
提问于 2012-07-04 12:30:03
回答 6查看 772.1K关注 0票数 302

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

代码语言:javascript
运行
复制
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变量中的所有东西是什么,或者如何使用它。我能帮个小忙吗?

EN

回答 6

Stack Overflow用户

回答已采纳

发布于 2012-07-04 16:08:46

如果你真的想用Python处理HTTP,我强烈推荐Requests: HTTP for Humans。根据你的问题改编的快速入门帖子是:

代码语言:javascript
运行
复制
>>> 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...
>>> 
票数 452
EN

Stack Overflow用户

发布于 2016-04-17 23:30:21

这是一个没有任何外部pip依赖的解决方案,但只能在Python 3+中工作(Python2不能工作):

代码语言:javascript
运行
复制
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)

示例输出:

代码语言:javascript
运行
复制
{
  "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"
}
票数 173
EN

Stack Overflow用户

发布于 2018-12-05 16:38:38

使用requests库通过命中REST API端点来获取、发布、放置或删除。在url中传递rest api端点url,在data中传递有效负载(Dict),在headers中传递标头/元数据

代码语言:javascript
运行
复制
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)
票数 18
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11322430

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档