我正在尝试在我的 ESP8266 上使用 WiFiClientSecure 发送 POST 请求。似乎连接本身有效,但是当我发送请求时,我收到以下消息:
<块引用>{"message":"文本为空(可能 HTTP/0.9)","traceId":"576eb1f7-3a18-7759-eaa1-8d0675f14fea"}
这是我发送请求的代码部分。知道我做错了什么(网络是我的 WiFiClientSecure 实例)?
if(!net.connect("xxx-ats.iot.eu-central-1.amazonaws.com", 8443)){
Serial.println("connection failed");
char err_buf[1024];
Serial.println(net.getLastSSLError(err_buf,1024));
Serial.printf("ssl_error: %s\n", err_buf);
return;
}else{
Serial.println("Yeah!");
}
net.print("POST /topics/gaswarner?qos=1 HTTP/1.1\n" \
"Host: xxx-ats.iot.eu-central-1.amazonaws.com:8443\n" \
"User-Agent: curl/7.74.0\n" \
"Accept: */*\n" \
"Content-Type: application/json\n" \
"Content-Length: 19\n\n" \
"{\"message\":\"hello\"}\n" \
"Connection: close\n\n");
Serial.println("Sent out..");
while (net.connected()) {
String line = net.readStringUntil('\n');
if (line == "\r") {
Serial.println("headers received");
break;
}
}
Serial.println("reply was:");
Serial.println("==========");
String line;
while(net.available()){
line = net.readStringUntil('\n'); //Read Line by Line
Serial.println(line); //Print response
}
Serial.println("==========");
Serial.println("closing connection");
使用 curl 发送该请求按预期工作:
<块引用>curl.exe -v -H "Content-Type: application/json" --tlsv1.2 --cacert "pathtoCaCert" --cert "pathToCert" --key "pathToKey" --request POST --data "{ "message": "Hello, world" }" "https://xxx-ats.iot.eu-central-1.amazonaws.com:8443/topics/gaswarner?qos=1"
提前致谢
答案 0 :(得分:0)
我测试了@hcheung 解决方案,它奏效了! 所以作为参考,我会在这里提供代码。请记住,使用 ESP8266HTTPClient 会是一个更简洁的解决方案:
net.print("POST /topics/gaswarner?qos=1 HTTP/1.1\n" \
"Host: xxx-ats.iot.eu-central-1.amazonaws.com:8443\n" \
"User-Agent: curl/7.74.0\n" \
"Accept: */*\n" \
"Content-Type: application/json\n" \
"Content-Length: 19\n" \
"Connection: close\n\n"\
"{\"message\":\"hello\"}\n");