我正在尝试使用ESP32向包含已设置的站点发送POST请求,其中包含2条数据。我试图使用网站“ reqbin.com”发送包含相同数据的POST请求,因此我认为数据本身不是问题。
下面是我的代码:
char ssid[] = "{{name}}";
char pass[] = "{{pass}}";
int port = 8080;
WiFiClient wifi;
void setup()
{
delay(1000);
WiFi.mode(WIFI_OFF); //Prevents reconnection issue (taking too long to connect)
delay(1000);
WiFi.mode(WIFI_STA); //This line hides the viewing of ESP as wifi hotspot
WiFi.begin(ssid, pass); //Connect to your WiFi router
Serial.println("");
Serial.print("Connecting");
// Wait for connection
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
}
//If connection successful show IP address in serial monitor
Serial.println("");
Serial.print("Connected to ");
Serial.println(ssid);
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
}
void loop()
{
String serverAddress = "sitename.com/data.php";
String contentType = "text/plain"
String postData = "t=26.1 h=25.6";
HttpClient http = HttpClient(wifi, serverAddress, port);
http.beginRequest(); //Specify request destination
int httpCode = http.post("/", contentType, postData);
Serial.println("httpCode = " + httpCode);
if (httpCode > 0)
{
String response = http.responseBody();
Serial.println("httpCode === " + httpCode);
Serial.println(response);
}
else
{
Serial.println("Error on POST request");
Serial.println(httpCode);
}
http.endRequest();
}
[使用reqbin时,我的状态为200,然后网站返回。但是,在ESP32上,它返回错误:
[E][WiFiGeneric.cpp:654] hostByName(): DNS Failed for sitename.com/data.php
我不确定请求的语法是否不正确。
更新:更改了我的循环并将服务器地址更改为此:
String serverAddress = "sitename.com";
String contentType = "text/plain";
String postData = "t=26.1 h=25.6";
HttpClient http = HttpClient(wifi, serverAddress, port);
http.beginRequest(); //Specify request destination
int httpCode = http.post("/data.php", contentType, postData);
Serial.println("httpCode = " + httpCode);
现在出现错误:
socket error on fd 57, errno: 104, "Connection reset by peer"
我想服务器需要url编码的数据,而不是纯文本。所以尝试在setup()之前定义以下内容
String serverAddress = "sitename.com"; HttpClient http = HttpClient(wifi, serverAddress, port);
并且在您的循环中,按照以下步骤构建帖子
String contentType = "application/x-www-form-urlencoded"; String postData = "?t=26.1&h=25.6"; http.post("/data.php", contentType, postData);
然后读取响应
// read the status code and body of the response statusCode = http.responseStatusCode(); response = http.responseBody(); Serial.print("Status code: "); Serial.println(statusCode); Serial.print("Response: "); Serial.println(response);
如果可行,用char数组替换String类