写一个利用esp8266连接B站api获取B站粉丝数的代码
时间: 2024-02-12 17:06:11 浏览: 138
ESP_VFD_Clock:ESP8266驱动的ИВ-18八位VFD时钟及B站粉丝数显
好的,以下是一个使用ESP8266连接B站API获取B站粉丝数的示例代码:
```
#include <ESP8266WiFi.h>
#include <WiFiClientSecure.h>
const char* ssid = "Your_SSID"; // 替换为你的Wi-Fi网络名称
const char* password = "Your_PASSWORD"; // 替换为你的Wi-Fi网络密码
const char* host = "api.bilibili.com";
const int httpsPort = 443;
String path = "/x/relation/stat?vmid=Your_UID"; // 替换为你的B站用户UID
void setup() {
Serial.begin(115200);
delay(10);
// 连接Wi-Fi网络
Serial.println();
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void loop() {
WiFiClientSecure client;
Serial.print("Connecting to ");
Serial.println(host);
if (!client.connect(host, httpsPort)) {
Serial.println("Connection failed");
return;
}
String url = "https://" + String(host) + path;
Serial.print("Requesting URL: ");
Serial.println(url);
client.print(String("GET ") + path + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"User-Agent: ESP8266\r\n" +
"Connection: close\r\n\r\n");
Serial.println("Request sent");
while (client.connected()) {
String line = client.readStringUntil('\n');
if (line == "\r") {
Serial.println("Headers received");
break;
}
}
String response = client.readStringUntil('\n');
Serial.print("Response: ");
Serial.println(response);
// 解析JSON响应
int index = response.indexOf("follower");
String followers = response.substring(index + 10, index + 16);
followers.replace(",", "");
Serial.print("Followers: ");
Serial.println(followers);
delay(5000); // 5秒更新一次
}
```
注意,这个程序需要先安装WiFiClientSecure库和ArduinoJson库。此外,你需要替换代码中的Wi-Fi网络名称、Wi-Fi网络密码、B站用户UID等参数。在程序运行时,它会连接到Wi-Fi网络,然后通过HTTPS连接到B站API获取用户的粉丝数,并将其显示在串口监视器中。你可以根据需要修改程序来显示其他信息或将结果发送到其他设备。
阅读全文