【Beetle ESP32 C6迷你开发板】--6.HTTP Client
<p> 本篇讲述开发板作为HTTP 客户端,与服务端通讯,获取消息文本。</p><p><strong><span style="color:#0000ff;">一.了解HTTP</span></strong></p>
<p> HTTP,超文本传输协议,是一个简单的请求-响应协议,它通常运行在TCP之上。它指定了客户端可能发送给服务器什么样的消息以及得到什么样的响应。请求和响应消息的头以<a data-from-module="summary" href="https://baike.baidu.com/item/ASCII/309296?fromModule=lemma_inlink" target="_blank">ASCII</a>形式给出;而消息内容则具有一个类似<a data-from-module="summary" href="https://baike.baidu.com/item/MIME/2900607?fromModule=lemma_inlink" target="_blank">MIME</a>的格式。</p>
<p> </p>
<p><strong><span style="color:#0000ff;">二.代码准备</span></strong></p>
<p>1.打开HTTP Client工程。</p>
<div style="text-align: center;"></div>
<div style="text-align: center;">图1:打开HTTP Client工程</div>
<p>2.初始化,添加路由账号密码</p>
<div style="text-align: center;"></div>
<div style="text-align: center;">图2:初始化,添加路由AP账号密码</div>
<p>3.运行主程序。连接上WiFi后,设置服务端url,Get消息,获取成功则将消息打印出来,获取失败打印失败码。</p>
<pre>
<code>void loop() {
// wait for WiFi connection
if ((wifiMulti.run() == WL_CONNECTED)) {
USE_SERIAL.print("Wifi connected!\n");
HTTPClient http;
USE_SERIAL.print(" begin...\n");
// configure traged server and url
//http.begin("https://www.howsmyssl.com/a/check", ca); //HTTPS
http.begin("http://example.com/index.html");//HTTP
USE_SERIAL.print(" GET...\n");
// start connection and send HTTP header
int httpCode = http.GET();
// httpCode will be negative on error
if (httpCode > 0) {
// HTTP header has been send and Server response header has been handled
USE_SERIAL.printf(" GET... code: %d\n", httpCode);
// file found at server
if (httpCode == HTTP_CODE_OK) {
String payload = http.getString();
USE_SERIAL.println(payload);
}
} else {
USE_SERIAL.printf(" GET... failed, error: %s\n", http.errorToString(httpCode).c_str());
}
http.end();
}
delay(5000);
}</code></pre>
<p>4.HTTP Client码可在HTTPClient.h头文件中看到定义,包括经典的404</p>
<div style="text-align: center;"></div>
<div style="text-align: center;">图3:HTTP Code</div>
<p><strong><span style="color:#0000ff;">三.测验</span></strong></p>
<p> 编译烧录后,打开串口.可看到初始化连接WIFI成功,客户端GET服务端消息成功会将消息打印,失败会打印出原因。日志如下</p>
<div style="text-align: center;">
<div style="text-align: center;"></div>
<p> </p>
</div>
<div style="text-align: center;">图4</div>
<p> 至此,成功运行HTTPClient功能。</p>
<p> </p>
<p>完美,成功运行HTTPClient功能,,,</p>
页:
[1]