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

时间:2016-04-04 13:49:50

标签: java rest azure azure-iot-hub azure-iot-sdk

我是azure iot的新手。我正在尝试使用其余的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

任何人都可以帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:1)

根据Azure IoTHub的官方文档Common error codes,错误代码400表示"请求正文无效;例如,它无法解析,或者无法验证对象。"。

我检查了代码中的policyold字符串值,然后我发现json字符串错过了所需的元素Sku name& Units。请仔细查看Json请求内容末尾下面的元素表。

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

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