如何在Python中进行POST请求

19

以下是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" and 'single' quotes"}'

不幸的是,我也无法弄清楚(像从cli中使用curl那样)。尽管我想用Python发送这个请求。 我该怎么做?


1
你试过一个叫做pycurl的库吗?它实际上是curl的仿真,具有完全相同的设置和几乎相同的语法。 - Vedaad Shakib
1个回答

39

使用标准的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)

1
我两个都用过,但我更喜欢Requests,它更简单。 - Juan Antonio
2
只是提醒一下,requests 提供了内置函数来解析 JSON 响应体:respJsonDict = r.json() - Alexey Antonenko
7
如果payload是json数据结构,请求示例中应该写成json=payload而不是data=payload,像这样... - raoulsson

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接