我想在 Python 中执行 curl 命令。
通常,我只需要在终端中输入命令并按回车键即可。但是,我不知道它在 Python 中是如何工作的。
命令显示如下:
curl -d @request.json --header "Content-Type: application/json" https://www.googleapis.com/qpxExpress/v1/trips/search?key=mykeyhere
有一个 request.json
文件要发送以获得响应。
我搜索了很多并感到困惑。我试图写一段代码,虽然我不能完全理解它并且它没有工作。
import pycurl
import StringIO
response = StringIO.StringIO()
c = pycurl.Curl()
c.setopt(c.URL, 'https://www.googleapis.com/qpxExpress/v1/trips/search?key=mykeyhere')
c.setopt(c.WRITEFUNCTION, response.write)
c.setopt(c.HTTPHEADER, ['Content-Type: application/json','Accept-Charset: UTF-8'])
c.setopt(c.POSTFIELDS, '@request.json')
c.perform()
c.close()
print response.getvalue()
response.close()
错误消息是 Parse Error
。如何正确获得服务器的响应?
原文由 Qiang Fu 发布,翻译遵循 CC BY-SA 4.0 许可协议
为了简单起见,您应该考虑使用 Requests 库。
JSON 响应内容的示例类似于:
如果您要查找更多信息,在 快速入门 部分,他们有很多工作示例。
对于您的特定 curl 翻译: