我有一个nodejs/高速公路后端服务,我希望使用端点注册我的设备。我必须用一些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;
}
}发布于 2016-06-17 17:30:28
你的要求几乎是正确的。HTTP消息规范声明在每个头端都需要一个CR+LF对(这是您拥有的),然后为了表示body start,您有一个只包含一个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 as内响应。如果没有,您的代码将永远不会打印响应,并且它将丢失。您可以这样做,以确保它在放弃响应之前至少要等待一定的时间。
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代码。您可以找到一些使用it的示例,这里。
https://stackoverflow.com/questions/37883865
复制相似问题