Basic operations of ESP8266 network client-02-Use WiFiClient library to implement network communication
String httpRequest = String("GET /") + " HTTP/1.1\r\n" + "Host:" + host + "\r\n" + "Connection: close\r\n" + "\r\n";
\r represents the Enter key.
\n is a line break, starting a new line.
"\r\n" tells the server the end of each line of request information.
The last "\r\n" indicates the end of the entire request content
#include <ESP8266WiFi.h>
const char* host = "www.example.com";//网络服务其地址
const int port = 80;//端口号
//WiFi信息
const char* ssid = "1124";
const char* password = "11241124";
void setup(){
Serial.begin(9600);
Serial.println("");
WiFi.mode(WIFI_STA);
WiFi.begin(ssid,password);
Serial.println("WiFi Start Coonnect");
while(WiFi.status() != WL_CONNECTED){
delay(1000);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi Connected");
WifiClientRequest();
}
void loop(){
}
void WifiClientRequest(){
//建立WiFi客户端对象
WiFiClient wifiClient;
//建立字符串,用于http请求
/*
GET / HTTP/1.1
Host:www.example.com
Connection: close
*/
String httpRequest = String("GET /") + " HTTP/1.1\r\n" + "Host:" + host + "\r\n" + "Connection: close\r\n" + "\r\n";
Serial.print("Connecting to: ");
Serial.println(host);
if(wifiClient.connect(host,port)){
Serial.println("Connect Success!");
//向服务器发送http请求
wifiClient.print(httpRequest);
Serial.println("Sending request: ");
Serial.println(httpRequest);
Serial.println("Web Server Response:");
while(wifiClient.connected() || wifiClient.available()){
if(wifiClient.available()){
String lineData = wifiClient.readStringUntil('\n');
Serial.println(lineData);
}
}
wifiClient.stop();
Serial.print("DisConnected from ");
Serial.println(host);
}else{
Serial.println("Connect Failed!");
wifiClient.stop();
}
}