BasicHttpClient.ino 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. /*
  2. *******************************************************************************
  3. * Copyright (c) 2022 by M5Stack
  4. * Equipped with M5Core sample source code
  5. * 配套 M5Core 示例源代码
  6. * Visit for more information: https://docs.m5stack.com/en/core/gray
  7. * 获取更多资料请访问: https://docs.m5stack.com/zh_CN/core/gray
  8. *
  9. * Describe: BasicHTTPClient.
  10. * Date: 2021/8/4
  11. ******************************************************************************
  12. */
  13. #include <Arduino.h>
  14. #include <HTTPClient.h>
  15. #include <M5Stack.h>
  16. #include <WiFi.h>
  17. #include <WiFiMulti.h>
  18. WiFiMulti wifiMulti;
  19. HTTPClient http;
  20. void setup() {
  21. M5.begin(); // Init M5Core. 初始化 M5Core
  22. M5.Power.begin(); // Init power 初始化电源模块
  23. wifiMulti.addAP(
  24. "M5-",
  25. "Of"); // Storage wifi configuration information. 存储wifi配置信息
  26. M5.Lcd.print("\nConnecting Wifi...\n"); // print format output string on
  27. // lcd. 串口格式化输出字符串
  28. }
  29. void loop() {
  30. M5.Lcd.setCursor(0, 0); // Set the cursor at (0,0). 设置光标位于(0,0)处
  31. if ((wifiMulti.run() ==
  32. WL_CONNECTED)) { // wait for WiFi connection. 等待连接至wifi
  33. M5.Lcd.print("[HTTP] begin...\n");
  34. http.begin(
  35. "http://example.com/index.html"); // configure traged server and
  36. // url. 配置被跟踪的服务器和URL
  37. M5.Lcd.print("[HTTP] GET...\n");
  38. int httpCode = http.GET(); // start connection and send HTTP header.
  39. // 开始连接服务器并发送HTTP的标头
  40. if (httpCode >
  41. 0) { // httpCode will be negative on error. 出错时httpCode将为负值
  42. M5.Lcd.printf("[HTTP] GET... code: %d\n", httpCode);
  43. if (httpCode ==
  44. HTTP_CODE_OK) { // file found at server. 在服务器上找到文件
  45. String payload = http.getString();
  46. M5.Lcd.println(payload); //打印在服务器上读取的文件. Print
  47. // files read on the server
  48. }
  49. } else {
  50. M5.Lcd.printf("[HTTP] GET... failed, error: %s\n",
  51. http.errorToString(httpCode).c_str());
  52. }
  53. http.end();
  54. } else {
  55. M5.Lcd.print("connect failed");
  56. }
  57. delay(5000);
  58. M5.Lcd.clear(); // clear the screen. 清除屏幕
  59. }