python 请求:对 Azure 的 PUT 请求失败,出现 415 错误

python requests: PUT request to azure fails with 415 error

所以我正在尝试使用 python 请求向 Azure 发出 PUT 请求(到 create/update 通知中心 - 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\'从哪里来的?
我明确地为那个请求设置了 headers,那个请求不包括在内……我一无所知。

我已经在上面提到的 Azure 页面上尝试了 "Try" 功能,您可以在其中尝试自己构建 body,但它有问题...

感谢您的帮助!

HTTP header 应该 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)