《ESP8266 学习笔记》 之 HTTPClient 移植 B站个人主页数据请求

目录

简介:

代码:

程序效果(9600波特率):


简介:

最近闲来无事,又去把 博哥 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,然而我没发过视频,哈哈哈!)!

猜你喜欢

转载自blog.csdn.net/qq_41868901/article/details/105421849