參考: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);
}
