使用 Rest 在 Azure IoT 中心创建共享访问策略 API

Shared Access Policy Creation in Azure IoT Hub using Rest API

我是 Azure 物联网的新手。我正在尝试使用其其余部分 api.

在 azure iot hub 中创建共享访问策略
 https://management.azure.com/subscriptions/{subscription-Id}/resourceGroups/{group-name}/providers/Microsoft.Devices/IotHubs/{hub-name}?api-version=2016-02-03");

我的 java 密码是

     String policyold = "{\"tags\" : {}, \"location\": \"East Asia\",\"properties\" : \"authorizationPolicies\" : [{\"name\" : \"policy-namw\", \"primaryKey\" : \"{mykey}\" ,\"secondaryKey\" : \"secondary-key\" ,\"permissions\" :[\"ServiceConnect\" ,\"RegistryRead\" ,\"RegistryWrite\" ,\"DeviceConnect\"]}],\"eventHubEndpoints\" : { \"events\" : {\"messageRetentionInDays\":\"2\"}}}";


    StringEntity input1 = new StringEntity(policyold);
    input1.setContentType("application/json");
    input1.setContentEncoding("UTF8");
    put.setEntity(input1);

    put.setHeader("Authorization", token);
    HttpResponse r2 = httpclient2.execute(put);
    System.out.println(r2.getStatusLine());
    String content2 = EntityUtils.toString(r2.getEntity());
    org.json.JSONObject recvObj2 = new org.json.JSONObject(content2);

但我遇到了以下错误。

 HTTP/1.1 400 Bad Request  {"error":{"code":"InvalidRequestContent","message":"The request content was invalid and could not be deserialized: 'Error converting value \"authorizationPolicies\" to type 'System.Collections.Generic.Dictionary`2[System.String,Newtonsoft.Json.Linq.JToken]'. Path 'properties', line 1, position 76.'."}}

而且我正在使用这个教程。https://msdn.microsoft.com/en-us/library/mt589015.aspx

谁能帮我解决这个问题?

根据 Azure IoTHub 的官方文档 Common error codes,错误代码 400 表示 "The body of the request is not valid; for example, it cannot be parsed, or the object cannot be validated."。

我检查了您代码中的 policyold 字符串值,然后我发现 json 字符串缺少必需的元素 Sku nameUnits。请仔细查看Json请求内容末尾下方的table元素

一个 Azure IoTHub 可以拥有多个共享访问策略。

因此,如果在创建新的 IoTHub 时创建共享访问策略,请使用 REST API Create a new IoT Hub, else use the REST API Update metadata on an existing IoT Hub 为现有的 IoTHub 添加一个新的。