【问题标题】:HTTP POST using Arduino ESP8266 SparkFun Shield使用 Arduino ESP8266 SparkFun Shield 的 HTTP POST
【发布时间】:2015-12-23 02:32:06
【问题描述】:

我正在尝试将 POST HTTP 发送到运行 node.js 的本地服务器。 GET 请求运行良好。使用 Postman(本地)的 POST 效果很好,我没有任何防火墙。但我不能用 Arduino 运行它。

我使用的代码是一个简单的 SparkFun 客户端示例,其中我只将 GET 更改为 POST:

void clientDemo() {
  // To use the ESP8266 as a TCP client, use the 
  // ESP8266Client class. First, create an object:
  ESP8266Client client;

  // ESP8266Client connect([server], [port]) is used to 
  // connect to a server (const char * or IPAddress) on
  // a specified port.
  // Returns: 1 on success, 2 on already connected,
  // negative on fail (-1=TIMEOUT, -3=FAIL).
  int retVal = client.connect(destServer, 5000);
  if (retVal == -1) {
    Serial.println(F("Time out"));
    return;
  } else if(retVal == -3) {
    Serial.println(F("Fail connection"));
    return;
  } else if(retVal == 1) {
    Serial.println("Connected with server!");
  }

  // print and write can be used to send data to a connected
  // client connection.
  client.print(httpPost);

  // available() will return the number of characters
  // currently in the receive buffer.
  while (client.available())
    Serial.write(client.read()); // read() gets the FIFO char

  // connected() is a boolean return value - 1 if the 
  // connection is active, 0 if it's closed.
  if (client.connected())
    client.stop(); // stop() closes a TCP connection.
}

httpPost 是:

const String httpPost = "POST /meteo HTTP/1.1\n"
                        "Host: 192.168.0.131:5000\n"
                        "User-Agent: Arduino/1.0\n"
                        "Connection: close\n"
                        "Content-Type: application/x-www-form-urlencoded;\n"
                          "windspeedmph=0&winddir=0&humidity=0&temp=0&pressure=0\n";

我在串行监视器中得到的只是“与服务器连接!”...

我做错了什么?

【问题讨论】:

    标签: http post get arduino esp8266


    【解决方案1】:

    标题和正文之间需要有一个空行:

    const String httpPost =   "POST /meteo HTTP/1.1\r\n"
                              "Host: 192.168.0.131:5000\r\n"
                              "User-Agent: Arduino/1.0\r\n"
                              "Connection: close\r\n"
                              "Content-Type: application/x-www-form-urlencoded;\r\n"
                              "\r\n"
                              "windspeedmph=0&winddir=0&humidity=0&temp=0&pressure=0\n";
    

    此外,按照标准,您应该使用\r\n 来换行,而不仅仅是\n
    HTTP header line break style

    【讨论】:

    • 不幸的是它没有帮助。仍然只有“与服务器连接!”仅此而已。我什至没有在日志中看到任何 POST 尝试。
    【解决方案2】:

    在我的例子中,指定 Content-Length 字段也很重要。然后应用程序开始正常工作。如果没有 Content-Length 字段,接收方就看不到任何数据。 Content-Length 指定有效负载的长度,在您的情况下是字符串的长度:“windspeedmph=0&winddir=0&humidity=0&temp=0&pressure=0\n”。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多