首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用Arduino ESP8266 SparkFun屏蔽的HTTP POST

使用Arduino ESP8266 SparkFun屏蔽的HTTP POST
EN

Stack Overflow用户
提问于 2015-12-23 10:32:06
回答 2查看 5.9K关注 0票数 2

我正在尝试向运行node.js的本地服务器发送POST HTTP。GET请求运行良好。使用Postman (本地)的帖子工作得很好,我没有任何防火墙。但我不能和Arduino一起运行它。

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

代码语言:javascript
复制
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是:

代码语言:javascript
复制
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";

我在串行监视器上看到的只是“已连接到服务器!”...

我做错了什么?

EN

回答 2

Stack Overflow用户

发布于 2015-12-23 10:51:06

headers和body之间需要有一个空行:

代码语言:javascript
复制
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

票数 1
EN

Stack Overflow用户

发布于 2016-12-07 20:25:19

在我的例子中,指定-Length字段也很重要。然后,应用程序开始按其应有的方式工作。如果没有Content-Length字段,在接收端就看不到数据。Content-Length指定有效负载的长度,在本例中为字符串的长度:"windspeedmph=0&winddir=0&humidity=0&temp=0&pressure=0\n".

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34427740

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档