Aus*_*yan 17 post http arduino
我正在尝试将信息发布到我创建和托管的Web项目上的API.我不确定HTTP POST请求的确切格式是什么.每次我尝试时都会收到HTTP 400错误,并显示"动词无效"的消息.
示例代码:
byte server[] = {"our IP"}
..
..
client(server, 80)
..
..
client.println("POST /Api/AddParking/3");
Run Code Online (Sandbox Code Playgroud)
它连接到提供的IP地址没有任何问题,但我回到上面提到的HTTP错误代码400.我不确定我是否应该在我的POST或内容长度或任何其他信息之后包含HTTP版本.
小智 30
最初的问题已经回答,但仅供通过谷歌的人参考; 这里有一个更完整的例子,说明如何使用Arduino将数据发布到Web服务器:
IPAddress server(10,0,0,138);
String PostData = "someDataToPost";
if (client.connect(server, 80)) {
client.println("POST /Api/AddParking/3 HTTP/1.1");
client.println("Host: 10.0.0.138");
client.println("User-Agent: Arduino/1.0");
client.println("Connection: close");
client.print("Content-Length: ");
client.println(PostData.length());
client.println();
client.println(PostData);
}
Run Code Online (Sandbox Code Playgroud)
另一种选择是使用 HTTPClient.h(适用于 adafruit 的 ESP32 Feather 上的 arduino IDE),它看起来可以毫不费力地处理 https。我还包括 JSON 有效负载,并且可以成功发送 IFTTT Webhook。
HTTPClient http;
String url="https://<IPaddress>/testurl";
String jsondata=(<properly escaped json data here>);
http.begin(url);
http.addHeader("Content-Type", "Content-Type: application/json");
int httpResponseCode = http.POST(jsondata); //Send the actual POST request
if(httpResponseCode>0){
String response = http.getString(); //Get the response to the request
Serial.println(httpResponseCode); //Print return code
Serial.println(response); //Print request answer
} else {
Serial.print("Error on sending POST: ");
Serial.println(httpResponseCode);
http.end();
}
Run Code Online (Sandbox Code Playgroud)
发送手工制作的 HTTP 数据包可能有点棘手,因为它们对所使用的格式非常挑剔。如果您有时间,我强烈建议您阅读HTTP 协议,因为它解释了所需的语法和字段。您尤其应该查看第 5 节“请求”。
关于您的代码,您确实需要在 POST URI 之后指定 HTTP 版本,并且我相信您还需要指定“Host”标头。最重要的是,您需要确保在每行末尾有一个回车换行符(CRLF)。所以,你的数据包应该是这样的:
POST /Api/AddParking/3 HTTP/1.1
Host: www.yourhost.com
Run Code Online (Sandbox Code Playgroud)