使用 WifiESP 库在带有 ESP8266 的 arduino 上发出 POST 请求 [英] POST request on arduino with ESP8266 using WifiESP library

查看:39
本文介绍了使用 WifiESP 库在带有 ESP8266 的 arduino 上发出 POST 请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 WifiESP 库发出 RESTful POST 请求(https://github.com/bportaluri/WiFiEsp).我能够使用 curl 成功发出请求,但使用 Arduino 和 ESP 始终出现错误.我怀疑问题与库所需的 POST 请求的手动格式有关,但我没有发现任何问题.这是我的消毒代码:

I am attempting to make RESTful POST request using the WifiESP library (https://github.com/bportaluri/WiFiEsp). I'm able to successfully make the request with curl, but consistently get an error using the Arduino and ESP. I suspect the problem is related to the manual formatting of the POST request the library requires, but I don't see anything wrong. Here my sanitized code:

if (client.connect(server, 80)) {
Serial.println("Connected to server");
// Make a HTTP request
String content = "{'JSON_key': 2.5}";   // some arbitrary JSON
client.println("POST /some/uri HTTP/1.1");
client.println("Host: http://things.ubidots.com");
client.println("Accept: */*");
client.println("Content-Length: " + sizeof(content));
client.println("Content-Type: application/json");
client.println();
client.println(content);
}

我得到的错误(通过串行监视器)是这样的:

The error I get (via serial monitor) is this:

Connected to server
[WiFiEsp] Data packet send error (2)
[WiFiEsp] Failed to write to socket 3
[WiFiEsp] Disconnecting 3

我成功的 curl 请求如下所示:

My successful curl requests looks like this:

curl -X POST -H "Content-Type: application/json" -d 'Some JSON' http://things.ubidots.com/some/uri

推荐答案

经过一些实验,这里是多个问题的解决方案.

After some experimentation, here is the solution to the multiple problems.

  1. JSON 对象的格式不正确.不接受单引号,所以我需要转义双引号.
  2. 主机在 POST 请求中不需要http://";POST 是一种 HTTP 方法.
  3. sizeof() 方法返回内存中变量的大小(以字节为单位),而不是字符串的长度.它需要被 .length() 替换.
  4. 将整数附加到字符串需要强制转换.

这是更正后的代码:

if (client.connect(server, 80)) {
  Serial.println("Connected to server");
  // Make the HTTP request
  int value = 2.5;  // an arbitrary value for testing
  String content = "{\"JSON_key\": " + String(value) + "}";
  client.println("POST /some/uri HTTP/1.1");
  client.println("Host: things.ubidots.com");
  client.println("Accept: */*");
  client.println("Content-Length: " + String(content.length()));
  client.println("Content-Type: application/json");
  client.println();
  client.println(content);
}

这篇关于使用 WifiESP 库在带有 ESP8266 的 arduino 上发出 POST 请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆