# HTTP-Client **Repository Path**: leisure27/HTTP-Client ## Basic Information - **Project Name**: HTTP-Client - **Description**: 使用HTTPClient库或WiFiClient库,访问API接口,获取时间、天气信息 - **Primary Language**: Unknown - **License**: Not specified - **Default Branch**: main - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2023-04-09 - **Last Updated**: 2023-05-04 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README ### 通过网络获取时间 * 设计参考:http://www.taichi-maker.com/homepage/esp8266-nodemcu-iot/iot-c/esp8266-nodemcu-web-client/http-request/ * 使用`ESP8266HTTPClient.h>`获取时间 * 使用ESP8266通过互联网向网络服务器(API接口)发送请求并且将API响应信息输出在屏幕上 * 使用`ESP8266HTTPClient库`和`WiFiClient库`均可以实现相同的功能,前者简单一些 ```c void get_time() { if (WiFi.status() == WL_CONNECTED) { HTTPClient http; // 重点1 创建 HTTPClient 对象 http.begin("http://quan.suning.com/getSysTime.do"); // 重点2 通过begin函数配置请求地址。 int httpCode = http.GET(); // 重点3 通过GET函数启动连接并发送HTTP请求 if (httpCode == HTTP_CODE_OK) { // 重点4. 如果服务器响应HTTP_CODE_OK(200)则从服务器获取响应体信息并通过串口输出 // 如果服务器不响应HTTP_CODE_OK(200)则将服务器响应状态码通过串口输出 String payload = http.getString(); // 获取响应信息 Serial.println(payload); http.end(); // 重点5. 关闭ESP8266与服务器连接 } } } ``` **同理,使用这种方法可以获取天气信息。** ### 示例程序 ```c++ #include #include #include const char *ssid = "leisure"; const char *password = "shadow27"; // 测试HTTP请求用的URL。注意网址前面必须添加"http://" #define URL "http://192.168.212.126/mjpeg/1" void httpClientRequest() { HTTPClient httpClient; // 创建 HTTPClient 对象 httpClient.begin(URL); // 请求地址,不用填端口号 int httpCode = httpClient.GET(); if (httpCode == HTTP_CODE_OK) { // 使用getString函数获取服务器响应体内容 String responsePayload = httpClient.getString(); Serial.println("Server Response Payload: "); Serial.println(responsePayload); } else { Serial.println("Server Respose Code:"); Serial.println(httpCode); } httpClient.end(); // 关闭与服务器的连接 } void setup() { Serial.begin(115200); WiFi.mode(WIFI_STA); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(1000); Serial.print("."); } Serial.println(""); Serial.print("WiFi Connected!"); httpClientRequest(); } void loop() {} ```