使用ESP8266WiFi库发送HTTP POST请求

dnn*_*agy 2 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)){
    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;
  }
}
Run Code Online (Sandbox Code Playgroud)

Daw*_*ion 7

您的要求几乎是正确的.该HTTP消息规格规定需要在每一个报头端处的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");
Run Code Online (Sandbox Code Playgroud)

此外,我会略微修改延迟,因为服务器可能无法在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);
}
Run Code Online (Sandbox Code Playgroud)

此外,如果您使用的是Arduino ESP8266环境,则会编写一个可以帮助您的HTTP客户端库,因此您不必编写此类低级HTTP代码.您可以在此处找到一些使用它的示例