Python urllib2 open request fails with urllib2.HTTPError: HTTP Error 401: Unauthorized

Python urllib2 open request fails with urllib2.HTTPError: HTTP Error 401: Unauthorized

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

添加下面的 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()

我终于明白问题出在哪里了。我对不阅读供应商手册缺乏耐心。我发送的 HTTP 请求缺少一些必需的参数,我也需要以加密格式发送密钥。