如何在python中发出post请求
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28467688/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to make post request in python
提问by frazman
Here is the curl command:
这是 curl 命令:
curl -H "X-API-TOKEN: <API-TOKEN>" 'http://foo.com/foo/bar' --data #
let me explain what goes into data
让我解释一下数据中的内容
POST /foo/bar
Input (request JSON body)
Name Type
title string
body string
So, based on this.. I figured:
所以,基于此..我想:
curl -H "X-API-TOKEN: " 'http://foo.com/foo/bar' --data '{"title":"foobar","body": "This body has both "double" and 'single' quotes"}'
curl -H "X-API-TOKEN: " ' http://foo.com/foo/bar' --data '{"title":"foobar","body": "这个 body 有 "double" 和'单'引号"}'
Unfortunately, I am not able to figure that out as well (like curl from cli) Though I would like to use python to send this request. How do i do this?
不幸的是,我也无法弄清楚(例如 cli 中的 curl),尽管我想使用 python 发送此请求。我该怎么做呢?
采纳答案by cangoektas
With the standard Python httplib
and urllib
libraries you can do
使用标准的 Pythonhttplib
和urllib
库,您可以做到
import httplib, urllib
headers = {'X-API-TOKEN': 'your_token_here'}
payload = "'title'='value1'&'name'='value2'"
conn = httplib.HTTPConnection("heise.de")
conn.request("POST", "", payload, headers)
response = conn.getresponse()
print response
or if you want to use the nice HTTP library called "Requests".
或者,如果您想使用名为"Requests"的不错的 HTTP 库。
import requests
headers = {'X-API-TOKEN': 'your_token_here'}
payload = {'title': 'value1', 'name': 'value2'}
r = requests.post("http://foo.com/foo/bar", data=payload, headers=headers)