如何在 python 中提出 post 请求

how to make post request in python

这是 curl 命令:

curl -H "X-API-TOKEN: <API-TOKEN>" 'http://foo.com/foo/bar' --data # 

让我解释一下数据的内容

POST /foo/bar
Input (request JSON body)

Name    Type    
title   string  
body    string

所以,基于此..我想:

curl -H "X-API-TOKEN: " 'http://foo.com/foo/bar' --data '{"title":"foobar","body": "This body has both "double"和 'single' 引号"}'

不幸的是,我也无法弄清楚(比如来自 cli 的 curl) 虽然我想使用 python 来发送这个请求。 我该怎么做?

使用标准 Python httpliburllib 库,您可以做到

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

或者如果您想使用名为 "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)