python要求:天蓝色的PUT要求失败,发生415错误

时间:2019-01-17 11:28:42

标签: python azure python-requests http-status-code-415

因此,我尝试使用python请求向Azure发出PUT请求(以创建/更新通知中心-https://docs.microsoft.com/en-us/rest/api/notificationhubs/notificationhubs/createorupdate#mpnscredential

我的代码:

url = "https://management.azure.com/subscriptions/mysub/resourceGroups/Default-NotificationHubs-WestEurope/providers/Microsoft.NotificationHubs/namespaces/myNamespace/notificationHubs/notificationHubName?api-version=2016-03-01"

bearer_token = "my very long token"

headers = {
    "dataType": "json",
    "accept":"application/json",
    "contentType":"application/json",
    "Authorization": "Bearer " + bearer_token }

filepath = "/Users/..../pathTo.p12"
    with open(filepath) as fh:
        byte_array_p12 = fh.read()

data = {
    'location': "West Europe",
    'properties.apnsCredential': {
        'properties.apnsCertificate': byte_array_p12,
        'properties.certificateKey': "some nice pass"
    }  
}

r = requests.put(url, data, headers = headers)

但是运行r给我415错误。

r.text
u'{"error":{"code":"UnsupportedMediaType","message":"The content media type \'application/x-www-form-urlencoded\' is not supported. Only \'application/json\' is supported."}}'

\'application/x-www-form-urlencoded\'来自哪里?
我正在为该请求显式设置标头,但其中不包含标头...我一无所知。

我已经尝试在上面提到的Azure页面上尝试“尝试”功能,您可以在其中尝试自己构造主体,但这是有问题的...

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

HTTP标头应为Content-Type,而不是contentType

headers = {
    "dataType": "json",
    "accept":"application/json",
    "Content-Type":"application/json",
    "Authorization": "Bearer " + bearer_token }

此外,参数data应该使用JSON编码。

r = requests.put(url, json=data, headers=headers)