我正在尝试将信息发布到我创建和托管的Web项目的API上。我不确定HTTP POST请求的确切格式是什么。每次我尝试都会收到HTTP 400错误,并显示“动词无效”的消息。
示例代码:
byte server[] = {"our IP"}
..
..
client(server, 80)
..
..
client.println("POST /Api/AddParking/3");
它连接到提供的IP地址没有任何问题,但我回到上面提到的HTTP错误代码400.我不确定我是否应该在POST或Content-Length之后包含HTTP版本或任何其他信息。
答案 0 :(得分:30)
最初的问题已经得到解答,但仅供通过Google访问的人参考;这里有一个更完整的例子,说明如何使用Arduino将数据发布到网络服务器:
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);
}
答案 1 :(得分:2)
发送手工制作的HTTP数据包可能有点棘手,因为它们对使用的格式非常挑剔。如果您有时间,我强烈建议您阅读HTTP protocol,因为它解释了所需的语法和字段。特别是你应该看第5节“请求”。
关于您的代码,您需要在POST URI之后指定HTTP版本,我相信您还需要指定“Host”标头。最重要的是,您需要确保在每一行的末尾都有一个回车换行符(CRLF)。因此,您的数据包应该类似于:
POST /Api/AddParking/3 HTTP/1.1
Host: www.yourhost.com
答案 2 :(得分:0)
请求也可以这样发送
// Check if we are Connected.
if(WiFi.status()== WL_CONNECTED){ //Check WiFi connection status
HTTPClient http; //Declare object of class HTTPClient
http.begin("http://useotools.com/"); //Specify request destination
http.addHeader("Content-Type", "application/x-www-form-urlencoded", false, true);
int httpCode = http.POST("type=get_desire_data&"); //Send the request
Serial.println(httpCode); //Print HTTP return code
http.writeToStream(&Serial); // Print the response body
}
答案 3 :(得分:0)
另一种选择是使用HTTPClient.h(用于adafruit的ESP32羽毛上的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();
}