[英]Python urllib2 open request fails with urllib2.HTTPError: HTTP Error 401: Unauthorized
下面是我使用 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()
最后,我弄清楚了問題所在。 我對不閱讀供應商手冊缺乏耐心。 我發送的 HTTP 請求缺少一些必需的參數,我也需要以加密格式發送密鑰。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.