【发布时间】:2018-08-14 11:34:57
【问题描述】:
我需要通过 REST API 将一些二进制文件发布到服务器。我正在为此使用python requests lib。首先我打开获取cookies的会话,然后执行POST请求,但得到403错误。
import requests
url0 = "https://someUrl/api/v1"
url1 = "https://someUrl/api/v1/Action()"
headers = {
'X-CSRF-Token': "E8D648268586298FBB52900F85C13CDC",
'Authorization': "Basic User:Password_InBase64"
}
s = requests.Session()
responce = s.get(url0, headers=headers)
print("first request")
print(responce.status_code)
headers = {
'X-CSRF-Token': "E8D648268586298FBB52900F85C13CDC",
}
payload = "{\"BinaryFile\": \"fileInBinary\"}"
response = s.post(url1, data=payload, headers=headers )
print("second request")
print(response.status_code)
print(response.headers)
响应 403 错误,我看不到任何信息,为什么会发生错误。您可以在下面看到控制台输出
first request
200
second request
403
{'X-CSRF-Token': 'Required', 'Content-Type': 'text/html;charset=utf-8',
'Content-Language': 'en', 'Content-Length': '762', 'Date': 'Tue, 14 Aug
2018 10:43:13 GMT', 'Server': 'SAP', 'Strict-Transport-Security': 'max-
age=31536000; includeSubDomains; preload'}
【问题讨论】:
-
您应该向 API 的提供者索取文档。 BTW 难怪 GET 请求有效。 CSRF 令牌主要用于更改操作。
标签: python rest api python-requests