【问题标题】:Getting 403 forbidden for POST RequestPOST 请求被禁止获取 403
【发布时间】: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


【解决方案1】:

与 API 提供者确认允许使用哪些方法(POST、GET)。 此外,如果第二个端点 (url1) 上有任何 IP 限制。

我建议使用任何类似应用程序的 PostMan 来发出请求 - 当一切正常时,您总是可以看到它在代码中的外观。

【讨论】:

    猜你喜欢
    • 2019-09-03
    • 2019-01-26
    • 1970-01-01
    • 2019-04-01
    • 2022-01-18
    • 2020-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多