我正在处理与IoT Hub连接的EventHub的消息。我将尝试解释整个过程。
使用终端,将以下命令发送到部署在Azure上的IoT中心组件:
curl --request POST \
--url "https://${IOT_HUB}.azure-devices.net/devices/${DEVICE}/messages/events?api-version=2018-06-30" \
--header "Accept: application/json" \
--header "Authorization: ${SAS_TOKEN}" \
--data "{ \"field1\" : \"12345\", \"field2\" : \"abcde\" }" \
--verbose
[当Azure函数接收事件(curl-> IoT中心-> Event-hub
@FunctionName("processSensorData")
public void processSensorData(
@EventHubTrigger(
name = "demo",
eventHubName = "", // blank because the value is included in the connection string
cardinality = Cardinality.ONE,
connection = "EventHubConnectionString")
String item,
final ExecutionContext context) {
context.getLogger().info("Event hub message received: " + item.toString());
我在控制台中收到以下消息:
[
{
"id":"xxx",
"topic":"/SUBSCRIPTIONS/xxx/RESOURCEGROUPS/xxxPROVIDERS/MICROSOFT.DEVICES/IOTHUBS/Txxxx",
"subject":"devices/xxx",
"eventType":"Microsoft.Devices.DeviceTelemetry",
"eventTime":"2020-04-13T15:02:15.253Z",
"data":{
"properties":{
},
"systemProperties":{
"iothub-content-type":"application/x-www-form-urlencoded",
"iothub-content-encoding":"",
"iothub-connection-device-id":"xxx",
"iothub-connection-auth-method":"{\"scope\":\"device\",\"type\":\"sas\",\"issuer\":\"iothub\",\"acceptingIpFilterRule\":null}",
"iothub-connection-auth-generation-id":"xxx",
"iothub-enqueuedtime":"2020-04-13T15:02:15.253Z",
"iothub-message-source":"Telemetry"
},
"body":"yyy"
},
"dataVersion":"",
"metadataVersion":"1"
}]
但主体似乎已加密。
如何解码正文以返回原始请求?
"{ \"field1\" : \"12345\", \"field2\" : \"abcde\" }"
非常感谢
胡安·安东尼奥
正文是base64 URL编码的。您应该在代码中对其进行解码,然后解析出JSON对象。尝试使用以下代码进行解码:
var base64EncodedBytes = System.Convert.FromBase64String(base64EncodedData);
var jsonStr = System.Text.Encoding.UTF8.GetString(base64EncodedBytes);