使用ESP8266WiFi库

时间:2016-06-17 14:15:40

标签: 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;
  }
}

1 个答案:

答案 0 :(得分:7)

您的请求几乎正确无误。 HTTP Message Spec表示你需要在每个标题端有一个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");

另外,我会略微修改延迟,因为服务器可能在10ms内没有响应。如果没有,您的代码将永远不会打印响应,它将丢失。你可以做一些事情,以确保它在放弃回复之前至少等待一段时间

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);
}

此外,如果你正在使用Arduino ESP8266环境,他们有一个 编写的HTTP客户端库可以帮助您,因此您不必编写此类低级HTTP代码。您可以找到一些使用它的示例here