使用Arduino进行HTTP POST请求

22
我正在尝试向我创建和托管的Web项目上的API发布信息。我不确定HTTP POST请求的确切格式是什么。每次尝试时,我都会收到HTTP 400错误消息,指出存在“无效动词”。
示例代码:
byte server[] = {"our IP"}
..
..

client(server, 80)
..
..
client.println("POST /Api/AddParking/3");

它连接到提供的IP地址没有任何问题,但是我收到了上述HTTP错误代码400。我不确定在我的POST之后是否应该包含HTTP版本或Content-Length或任何其他信息。

4个回答

33

原问题已经得到解答,但是为了给通过谷歌搜索的人提供参考,这里提供一个更完整的示例,说明如何使用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);
}

2
client.println(PostData.length()); 缺少't' - F481
嗨,我觉得在“Host: 10.0.0.138”参数中输入哪个主机似乎并不重要。只要在client.connect(server, port)行中服务器正确即可。这个“Host:”参数无关紧要吗? - teeeeee
这个 Content-Length 标头是我在 Heroku 上让它正常工作的关键。 - SRR

6

另一个选择是使用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();

 }

2
发送手工制作的HTTP数据包可能有些棘手,因为它们对使用的格式非常挑剔。如果您有时间,我强烈建议阅读HTTP协议,因为它解释了所需的语法和字段。特别是您应该查看第5节"请求"。
关于您的代码,您确实需要在POST URI之后指定HTTP版本,我认为您还需要指定"Host"头。此外,您需要确保每行末尾都有回车换行符(CRLF)。因此,您的数据包应该类似于:
POST /Api/AddParking/3 HTTP/1.1
Host: www.yourhost.com

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

}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接