带d的Python 2 post请求

2024-10-02 20:29:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在开发一个可以使用Curl的API,命令如下所示:

curl -X POST --header 'Content-Type: application/json' --header 'Accept: application/json' --header 'api_key: someKey' -d '{
  "configurationPath": "/a/b",
  "entityTypesFilter": [
    "Filter1"
  ],  
  "pageSize": 10 
}' 'http://localhost:123/ab/rest/v1/entities'

如何使用请求库将其转换为Python2代码

我试过这样的方法:

import requests
headers = {'api_key': 'someKey'}
url = "http://localhost:123/ab/rest/v1/entities"

data = {
  "configurationPath": "/a/b",
  "entityTypesFilter": [
    "Filter1"
  ],  
  "pageSize": 10 
}

r = requests.post(url, headers=headers, data = data)
print r.content

但这就产生了415个错误:

> Status Report</p><p><b>Message</b> Unsupported Media Type</p><p><b>Description</b> The origin server is refusing to se
rvice the request because the payload is in a format not supported by this method on the target resource.</p><hr class="
line" /><h3>Apache Tomcat/9.0.8</h3></body></html>

如何修复?我相信它是data部分的格式,但不确定需要什么以及如何修改以使其工作。
谢谢


Tags: thekeyapijsonhttpdataapplicationtype
1条回答
网友
1楼 · 发布于 2024-10-02 20:29:46

curl命令以JSON格式发送数据,内容类型为application/JSON;你的Python代码没有这样做

如果使用json参数而不是data,请求将执行此操作:

r = requests.post(url, headers=headers, json=data)

相关问题 更多 >