Arduino ESP32 发送HTTP请求 TCP Client 获取苏宁服务器时间

参考:https://www.qutaojiao.com/8043.html

ESP8266的HTTP请求:http://www.taichi-maker.com/homepage/iot-development/iot-dev-reference/esp8266-c-plus-plus-reference/esp8266httpclient/

Arduino中的示例HTTPClient中的BasicHTTPClient和BasicHTTPSClient可以作为参考

#include <WiFi.h>
#include <HTTPClient.h>
 
const char* ssid = "hg2020";
const char* password =  "12345678";
 
void setup() {
 
  Serial.begin(115200);
  delay(400);
  WiFi.begin(ssid, password);
 
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to WiFi..");
  }
 
  Serial.println("Connected to the WiFi network");
 
}
 
void loop() {
 
  if ((WiFi.status() == WL_CONNECTED)) { //Check the current connection status
 
    HTTPClient http;
 
    http.begin("http://quan.suning.com/getSysTime.do"); //Specify the URL
    int httpCode = http.GET();                                        //Make the request
 
    if (httpCode > 0) { //Check for the returning code
 
        String payload = http.getString();
        Serial.println(httpCode);
        Serial.println(payload);
      }
 
    else {
      Serial.println("Error on HTTP request");
    }
 
    http.end(); //Free the resources
  }
 
  delay(1000);
 
}

ESP32去访问服务器还可以用TCP Client实现:参考

#include <WiFi.h>

const char *ssid = "********";
const char *password = "********";

const char *host = "www.example.com"; //欲访问的域名

void setup()
{
    Serial.begin(115200);
    Serial.println();

    WiFi.mode(WIFI_STA);
    WiFi.setSleep(false); //关闭STA模式下wifi休眠,提高响应速度
    WiFi.begin(ssid, password);
    while (WiFi.status() != WL_CONNECTED)
    {
        delay(500);
        Serial.print(".");
    }
    Serial.println("Connected");
    Serial.print("IP Address:");
    Serial.println(WiFi.localIP());
}

void loop()
{
    WiFiClient client; //声明一个客户端对象,用于与服务器进行连接

    Serial.println("尝试访问服务器");
    if (client.connect(host, 80)) //80为一般网站的端口号
    {
        Serial.println("访问成功");

        //向服务器发送请求头,请求网页数据
        //******作为WEB Client使用最核心的就是和WEB Server连接成功后发送相应的请求头请求数据******
        //******WEB Server在收到请求头后返回对应的数据,比如返回网页、图片、文本等******
        //******关于请求头可以参考之前的文章《从零开始的ESP8266探索(06)-使用Server功能搭建Web Server》******
        client.print(String("GET /") + " HTTP/1.1\r\n" +
                     "Host: " + host + "\r\n" +
                     "Connection: close\r\n" +
                     "\r\n");

        //以下代码将收到的网页数据按行打印输出
        //如果是常见的WEB Client(浏览器)的话会将收到的html文件渲染成我们一般看到的网页
        while (client.connected() || client.available()) //如果已连接或有收到的未读取的数据
        {
            if (client.available()) //如果有数据可读取
            {
                String line = client.readStringUntil('\n'); //按行读取数据
                Serial.println(line);
            }
        }

        client.stop(); //关闭当前连接
    }
    else
    {
        Serial.println("访问失败");
        client.stop(); //关闭当前连接
    }
    delay(10000);
}

  

posted @ 2020-12-27 11:14  天气之子A  阅读(2394)  评论(0编辑  收藏  举报