2016-04-04 64 views
0

我是新来的azure iot。我正尝试在Azure iot hub中使用其余api创建共享访问策略。使用Rest 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); 

,但我面临的followiing错误。

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

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

+0

我建议您可以查看Azure IoT中心Java SDK以简化API调用。链接是在https://github.com/Azure/azure-iot-sdks/tree/master/java – juvchan

+0

是的,我试图用它来创建共享访问策略。但找不到任何代码示例和文档用于此目的。这就是为什么我结束了HTTP休息API。你可以参考一个吗?谢谢 – Sadaf

回答

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添加一个新的IoTHub。

+0

好的@PeterPan。 现在我改变了我的policyold字符串。字符串policyold =“{\”tags \“:{},\”location \“:\”East Asia \“,\”properties \“:\”authorizationPolicies \“:[{\”name \“: \“primary_key \”:\“{mykey} \”,\“secondarykey \”:\“secondary-key \”,\“permissions \”:[\“ServiceConnect \ “RegistryRead \”,\“RegistryWrite \”,\“DeviceConnect \”]}],\“eventHubEndpoints \”:{\“events \”:{\“messageRetentionInDays \”:\“2 \”}}, SKU \ “:{\” 名称\ “:\” S1 \ “\ ”容量\“:1}}”; 但仍面临同样的问题。 – Sadaf

+0

我正在使用更新元数据和现有IoT中心Rest API。 – Sadaf

+0

@Sadaf我建议你可以尝试使用Java的Azure IoTHub SDK,因为Juvchan在评论中说,并且使用Fiddler来捕获HTTP请求和响应以了解REST API调用,因为Java SDK包装了相关的REST蜜蜂。 [可以参考Java的IoTHub教程](https://azure.microsoft.com/en-us/documentation/articles/iot-hub-java-java-getstarted/)。 –