使用HTTP POST请求从ESP8266向Live Server发送数据时出现问题

时间:2019-05-17 10:40:03

标签: php arduino httprequest esp8266 arduino-esp8266

我需要将数据从esp8266发送到000webhostapp。 使用https的000webhostapp与服务器的所有连接都可以正常工作,但是数据发送无法正常工作。

我尝试了几种代码。与获取请求或发布请求,但没有一个工作正常。我已经更改了esp或http的http版本,但这也行不通。

这是代码

#include "DHTesp.h"
#include "ESP8266WiFi.h"
#include <ESP8266WebServer.h>
#include <ESP8266HTTPClient.h>
#ifdef ESP32
#pragma message(THIS EXAMPLE IS FOR ESP8266 ONLY!)
#error Select ESP8266 board.
#endif

DHTesp dht;
const char* ssid = "*****";
const char* password =  "****";
const char server[] = "biracial-conspiracy.000webhostapp.com";  
WiFiClient client;
void setup()
{
  Serial.begin(9600);
  Serial.println();
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);             // Connect to the network
  Serial.print("Connecting to ");
  Serial.print(ssid); Serial.println(" ...");

  int i = 0;
  while (WiFi.status() != WL_CONNECTED) { /* Wait for the Wi-Fi to 
    connect*/
    delay(1000);
    Serial.print(++i); Serial.print(' ');
  }

  Serial.println("wl connected");
  Serial.println("");
  Serial.println("Credentials accepted! Connected to wifi\n ");
  Serial.println("");



  Serial.println("Status\tHumidity (%)\tTemperature (C)\t(F)\tHeatIndex 
  (C)\t(F)");
  dht.setup(2, DHTesp::DHT22); // Connect DHT sensor to GPIO 17
 }

 void loop()
 {

   if (client.connect(server, 80)) {
     Serial.println("connected to server");
     int humidity = dht.getHumidity();
     int temperature = dht.getTemperature();
     Serial.print("Humidity : ");
     Serial.print(humidity);
     Serial.print("\t");
     Serial.print(" Temperature in Celcius : ");
     Serial.print(temperature);
     Serial.print("\t");
     Serial.print(" Moisture: ");
     Serial.println(analogRead(A0));
     HTTPClient http;
     int moisture = analogRead(A0);

     String data = "temp=" + String(temperature) + "&moisture=" + 
    String(moisture) + "&humidity=" + String(humidity);
    client.println("POST firebase.php HTTP/1.1");
    client.println("Host: biracial-conspiracy.000webhostapp.com\n");
    client.println("User-Agent: ESP8266/1.0");
    client.println("connection: close");
    client.status();
    client.println("Content-Type: application/x-www-form-urlencoded");
    client.print("Content-Length: ");
    client.print(data.length());
    client.print("\n\n");
    client.print(data);
    delay(1000);
    Serial.println("\n");
    Serial.println("Data sending is : ");
    Serial.println(data);
    Serial.println("The byte is : ");
    Serial.println(data.length());
    client.stop();
   }
   else
   {
    Serial.println("Server Error.");
   }


 }

1 个答案:

答案 0 :(得分:1)

您不能使用WiFiClient连接到 HTTPS 。您需要使用带有TLS的客户端库(例如WiFiClientSecure)才能连接到HTTPS服务器。