Python urllib2打开请求因urllib2而失败。HTTPError:HTTP错误401:未经授权

问题描述 投票:0回答:1

以下是我使用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()
python urllib2
1个回答
0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.