ESP8266网络客户端基本操作-使用ESP8266HTTPClient库实现网络通讯
www.example.com为测试网址,复制到浏览器打开。可改为自己的服务器地址
/*
* 使用ESP8266HTTPClient库实现网络通讯
*/
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
//测试网址
#define testUrl "http://www.example.com"
//wifi信息
const char* ssid = "1124";
const char* password = "11241124";
void setup(){
//串口设置
Serial.begin(9600);
//设置ESP8266为无线终端模式
WiFi.mode(WIFI_STA);
//开始连接WIFI
WiFi.begin(ssid,password);
//等待WIFI连接
while(WiFi.status() != WL_CONNECTED){
delay(1000);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi Connected!");
httpClientRequest();
}
void loop(){
}
//发送http请求并且将服务器响应通过串口输出
void httpClientRequest(){
//创建HTTPClient对象
HTTPClient httpClient;
//通过begin函数 配置请求地址
httpClient.begin(testUrl);
Serial.print("URL:");
Serial.println(testUrl);
//通过GET函数启动连接并发送HTTP请求
int httpCode = httpClient.GET();
Serial.print("Send GET request to URL:");
Serial.println(testUrl);
//根据服务器响应码进行对应处理
if(httpCode == HTTP_CODE_OK){
String responsePayload = httpClient.getString();
Serial.print("Server Response Payload:");
Serial.println(responsePayload);
}else{
Serial.print("Server Response Code:");
Serial.println(httpCode);
}
//关闭ESP8266与服务器的连接
httpClient.close();
}