Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/arduino/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用ESP8266WiFi库发送HTTP POST请求_Http_Arduino_Http Post_Esp8266 - Fatal编程技术网

使用ESP8266WiFi库发送HTTP POST请求

使用ESP8266WiFi库发送HTTP POST请求,http,arduino,http-post,esp8266,Http,Arduino,Http Post,Esp8266,我有一个nodejs/expressjs后端服务,我希望使用端点注册我的设备。我必须用一些json编码的数据向我的服务器发送POST请求。我做这件事有困难。我可以成功地发送GET请求并从服务器获得响应,但是当我尝试发送POST请求时,没有得到响应。我是这样做的: //Make a post request void postRequest(const char* url, const char* host, String data){ if(client.connect(host, PORT

我有一个nodejs/expressjs后端服务,我希望使用端点注册我的设备。我必须用一些json编码的数据向我的服务器发送POST请求。我做这件事有困难。我可以成功地发送GET请求并从服务器获得响应,但是当我尝试发送POST请求时,没有得到响应。我是这样做的:

//Make a post request
void postRequest(const char* url, const char* host, String data){
  if(client.connect(host, PORT)){
    client.print(String("POST ") + url + " HTTP/1.1\r\n" +
                 "Host: " + host + "\r\n" +
                 //"Connection: close\r\n" +
                 "Content-Type: application/json\r\n" +
                 "Content-Length: " + data.length() + "\r\n" +
                 data + "\n");
    //Delay
    delay(10);

    // Read all the lines of the reply from server and print them to Serial
    CONSOLE.println("Response: \n");
    while(client.available()){
        String line = client.readStringUntil('\r');
        CONSOLE.print(line);
    }
  }else{
    CONSOLE.println("Connection to backend failed.");
    return;
  }
}
你的要求几乎是正确的。在每个头端需要一个CR+LF对的状态,你有,然后为了表示主体开始,你有一个只包含CR+LF对的空行

您的代码在额外的代码对中应该是这样的

client.print(String("POST ") + url + " HTTP/1.1\r\n" +
                 "Host: " + host + "\r\n" +
                 //"Connection: close\r\n" +
                 "Content-Type: application/json\r\n" +
                 "Content-Length: " + data.length() + "\r\n" +
                 "\r\n" + // This is the extra CR+LF pair to signify the start of a body
                 data + "\n");
另外,我会稍微修改延迟,因为服务器可能在10毫秒内没有响应。否则,您的代码将永远不会打印响应,并且将丢失响应。您可以这样做,以确保它在放弃响应之前至少等待一定的时间

int waitcount = 0;
while (!client.available() && waitcount++ < MAX_WAIT_COUNT) {
     delay(10);
}

// Read all the lines of the reply from server and print them to Serial
CONSOLE.println("Response: \n");
while(client.available()){
    String line = client.readStringUntil('\r');
    CONSOLE.print(line);
}
int waitcount=0;
而(!client.available()&&waitcount++
此外,如果您使用的是Arduino ESP8266环境,则它们具有 编写的HTTP客户端库可能会帮助您,所以您不必编写像这样的低级HTTP代码。你可以找到一些使用它的例子