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

查看:1005
本文介绍了使用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

我成功的卷曲请求如下所示:

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. 在字符串中附加一个整数需要强制转换。

  1. The JSON object was not correctly formatted. Single quotes were not accepted, so I needed to escape the double quotes.
  2. The host does not need "http://" in a POST request; POST is a HTTP method.
  3. The sizeof() method returns the size, in bytes, of the variable in memory rather than the length of the string. It needs to be replaced by .length().
  4. Appending an integer to a string requires a cast.

这是更正后的代码:

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天全站免登陆