目錄
簡介:
最近閒來無事,又去把 博哥 ESP8266的帖子刷了一遍,在看到 ESP8266開發之旅 網絡篇⑨ HttpClient——ESP8266HTTPClient庫的使用 時,對API的GIT請求有了不同的理解,於是將 B站個人主頁數據請求 的API 換上去,果然成功了,於是,謹以此文章記錄成功後的代碼!
代碼:
/**
* 功能:移植B站主頁數據進行GET請求
* @author 劉澤文
* @date 2020/4/9
*/
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#define DebugBegin(baud_rate) Serial.begin(baud_rate)
#define DebugPrintln(message) Serial.println(message)
#define DebugPrint(message) Serial.print(message)
#define DebugPrintf(message) Serial.printf(message)
const char* AP_SSID = "liuzewen"; //wifi ssid
const char* AP_PSK = "17609245102liu"; //wifi 密碼
const char* HOST = "http://api.bilibili.com";
const char* bilibili_ID = "277392717";
const char *keys[] = {"Content-Length","Content-Type","Connection","Date"};//需要收集的響應頭的信息
const unsigned long HTTP_TIMEOUT = 5000;
HTTPClient http;
String GetUrl;
String response;
void setup() {
WiFi.mode(WIFI_STA);
DebugBegin(9600);
DebugPrint("Connecting to ");
DebugPrintln(AP_SSID);
WiFi.begin(AP_SSID, AP_PSK);//連接wifi
WiFi.setAutoConnect(true);
while (WiFi.status() != WL_CONNECTED) {
//這個函數是wifi連接狀態,返回wifi鏈接狀態
delay(500);
DebugPrint(".");
}
DebugPrintln("");
DebugPrintln("WiFi connected");
DebugPrintln("IP address: " + WiFi.localIP());
//拼接get請求url(粉絲數:http://api.bilibili.com/x/relation/stat?vmid=277392717)需要請求粉絲數請取消註釋下面兩行
//GetUrl = String(HOST) + "/x/relation/stat?vmid=";
//GetUrl += String(bilibili_ID);
//拼接get請求url(播放量:http://api.bilibili.com/x/space/upstat?mid=277392717)需要請求播放量請取消註釋下面兩行
GetUrl = String(HOST) + "/x/space/upstat?mid=";
GetUrl += String(bilibili_ID);
//設置超時
http.setTimeout(HTTP_TIMEOUT);
//設置請求url
http.begin(GetUrl);
//設置獲取響應頭的信息
http.collectHeaders(keys,4);
}
void loop() {
//對B站主頁數據進行GET請求
int httpCode = http.GET();
if (httpCode > 0) {
Serial.printf("[HTTP] GET... code: %d\n", httpCode);
//判斷請求是否成功
if (httpCode == HTTP_CODE_OK) {
//讀取響應內容
response = http.getString();
DebugPrintln("Get the data from Internet!");
DebugPrintln(response);
DebugPrintln(String("Content-Length:")+ http.header("Content-Length"));
DebugPrintln(String("Content-Type:")+ http.header("Content-Type"));
DebugPrintln(String("Connection:")+ http.header("Connection"));
DebugPrintln(String("Date:")+ http.header("Date"));
}
} else {
Serial.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str());
}
http.end();
delay(1000);
}
注:程序中並未對GIT得到的Json數據進行解析,僅僅是簡單的打印Git的數據內容!
程序效果(9600波特率):
可以看到你的跟隨者(follower,也就是粉絲數,雖然我僅有兩個,哈哈!)!
可以看到我的視頻播放量(view,然而我沒發過視頻,哈哈哈!)!