如何在ESP32上使用http客户端请求进行正确的POST(错误:“站点名称DNS失败”)

问题描述 投票:0回答:1

我正在尝试使用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"
post arduino dns request esp32
1个回答
0
投票

我想服务器需要url编码的数据,而不是纯文本。所以尝试在setup()之前定义以下内容

 String response;
int statusCode = 0;

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类

char serverAddress[] = "www.test.com";  // server address
© www.soinside.com 2019 - 2024. All rights reserved.