Patebin api在python中为requests.post返回“错误的API请求,使用POST请求,而不是GET”?

问题描述

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

# 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 发布请求适用于我的 api 密钥,我得到了粘贴网址。

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

解决方法

我遇到了与您描述的相同的问题。我在 API 链接中使用 https 而不是 http 解决了这个问题。

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

,

正如@LeventeKovács 指出的那样,简单的解决方法是将 URL 中的请求类型从“http”更改为“https”。这就是为什么 Requests 库没有按照您当前的 URL 执行您想要/期望的操作...

您正在向 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'

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

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

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

301 Moved Permanently 如果收到 301 状态码作为响应 对于 GET 或 HEAD 以外的请求,用户代理不得 自动重定向请求,除非它可以被确认 用户,因为这可能会改变请求的条件 发出。注意:当自动重定向 POST 请求后 收到 301 状态码,一些现有的 HTTP/1.0 用户代理将 错误地将其更改为 GET 请求。

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