Pastebin api 为 python 中的 requests.post 返回 "Bad API request, use POST request, not GET"?

Patebin api returning "Bad API request, use POST request, not GET" for requests.post in python?

我正在尝试使用 python 中的 patebin api 使用 requests.post 发送 post 请求,我的代码是

# importing the requests library
import requests

# defining the api-endpoint
API_ENDPOINT = "http://pastebin.com/api/api_post.php"

# your API key here
API_KEY = "my api key"

# your source code here
source_code = '''
print("Hello, world!")
a = 1
b = 2
print(a + b)
'''

# data to be sent to api
data = {'api_dev_key':API_KEY,
        'api_option':'paste',
        'api_paste_code':source_code,
        'api_paste_format':'python'}

# sending post request and saving response as response object
r = requests.post(url = API_ENDPOINT, data = data)

# extracting response text
pastebin_url = r.text
print("The pastebin URL is:%s"%pastebin_url)

文档中给出的 curl post 请求适用于我的 api 密钥,我得到了粘贴 url.

但是我收到 错误的 API 请求,请使用 POST 请求,而不是 GET 上述 python 代码的输出 有人有吗任何建议

我遇到了和你描述的一样的问题。我在 API link 中使用 https 而不是 http.

解决了它

我的尝试建议是: API_ENDPOINT = "https://pastebin.com/api/api_post.php"

正如@LeventeKovács 指出的那样,简单的解决方法是将 URL 中的请求类型从“http”更改为“https”。这就是为什么 Requests 库无法使用您当前的 URL...

执行您 want/expect 的操作

您正在向 HTTPS 端点发出 HTTP 请求。这需要从 HTTP 重定向到 HTTPS。处理此重定向时,请求库将 POST 更改为 GET,代码如下:

# Second, if a POST is responded to with a 301, turn it into a GET.
# This bizarre behaviour is explained in Issue 1704.
if response.status_code == codes.moved and method == 'POST':
    method = 'GET'

这里是 link 与此代码相关的评论中提到的问题:

https://github.com/psf/requests/issues/1704

该问题引用了 HTTP 规范的这一部分:

301 Moved Permanently If the 301 status code is received in response to a request other than GET or HEAD, the user agent MUST NOT automatically redirect the request unless it can be confirmed by the user, since this might change the conditions under which the request was issued. Note: When automatically redirecting a POST request after receiving a 301 status code, some existing HTTP/1.0 user agents will erroneously change it into a GET request.

然后似乎通过说请求库应该做 most/all 浏览器当前所做的事情来继续合理化代码的行为,即将 POST 更改为 GET 并重试新地址。