【问题标题】:Python urllib2 open request fails with urllib2.HTTPError: HTTP Error 401: UnauthorizedPython urllib2 打开请求失败,出现 urllib2.HTTPError: HTTP Error 401: Unauthorized
【发布时间】:2020-04-16 04:24:44
【问题描述】:

下面是我使用 urllib2 库的 python 代码,尽管我使用了正确的 API 密钥,但它一直失败并出现未经授权的错误。如果我使用 curl,POST/GET 工作得很好。有人有想法吗?谢谢。

在下面添加 curl 命令就可以了

Create Credential 
curl -X POST 'https://myurl.com' \
     -H 'Content-Type: application/json' \
     -u 'XXXXXXXXXX:' \
     -d @- << EOF
{ 
  "vendorAccountId": "1234567",
  "type": "my_role"
}
EOF

下面是不起作用的python代码。 基本上,它失败的代码行是: response = opener.open(request)

import boto3
import json
import logging
import signal
import requests
from urllib2 import build_opener, HTTPHandler, Request
import urllib2


LOGGER = logging.getLogger()
LOGGER.setLevel(logging.INFO)


def main():
        auth_token = "XXXXXXXXXX"
        account_id = "1234567"
        request_type = "CreateCredentials"
        content_type = ""
        request_body = json.dumps({})

         if request_type == "CreateCredentials":
            target_url = 'https://myurl.com'
            request_method = "POST"
            content_type = "application/json"
            request_body = json.dumps({
                "vendorAccountId": account_id,
                "type": "my_role"
            })

        handler = urllib2.HTTPHandler()
        opener = urllib2.build_opener(handler)

        request = urllib2.Request(target_url, data=request_body)
        request.add_header("Content-Type", content_type)
        request.add_header("Content-Length", len(request_body))
        request.add_header("Authorization", auth_token)
        request.get_method = lambda: request_method
        response = opener.open(request) #*****Fails here******


if __name__ == "__main__":
    main()

【问题讨论】:

  • 如果你有一个工作的 curl 请求和一个不工作的 urllib2 请求,你可能应该首先弄清楚到底有什么区别(如果一个工作正常,另一个不工作,即使如果不是很明显)。
  • 是的,这就是我想要找出的。显然,urllib2 实现的问题没有按说明工作。我正在尝试对此进行更多调试?你有什么建议吗?我们如何打印请求参数?
  • 我完全不知道。如果您能弄清楚这一点并将其与您正在使用的 curl 调用添加到问题中,那么它至少应该让某人能够审查并为您指明正确的方向。
  • 在原题中添加了 curl 命令。

标签: python urllib2


【解决方案1】:

最后,我弄清楚了问题所在。我对不阅读供应商手册缺乏耐心。我发送的 HTTP 请求缺少一些必需的参数,我也需要以加密格式发送密钥。

【讨论】:

  • 很高兴你明白了!如果您可以添加让您感到困惑的信息,然后接受您自己的答案,那么对于其他可能会在将来遇到类似问题时发现此问题的人来说,这可能是一个很好的资源。
猜你喜欢
  • 2017-04-22
  • 1970-01-01
  • 1970-01-01
  • 2014-09-05
  • 2013-01-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-12
相关资源
最近更新 更多