1.示例程序
WebClient 軟件包提供兩個 HTTP Client 示例程序, 分別用於演示軟件包支持的 GET 和 POST 功能,完成數據的上傳與下載。
示例文件
示例程序路徑 | 說明 |
---|---|
samples/webclient_get_sample.c | GET 請求測試例程 |
samples/webclient_post_sample.c | POST 請求測試例程 |
2.準備工作
2.1獲取軟件包
-
menuconfig 配置獲取軟件包和示例代碼
打開 RT-Thread 提供的 ENV 工具,使用 menuconfig 配置軟件包。
啓用 WebClient 軟件包,並配置使能測試例程(Enable webclient GET/POST samples),如下所示:
RT-Thread online packages
IoT - internet of things --->
[*] WebClient: A HTTP/HTTPS Client for RT-Thread
[ ] Enable debug log output
[*] Enable webclient GET/POST samples # 開啓 WebClient 測試例程
[ ] Enable file download feature support
Select TLS mode (Not support) --->
Version (latest) ---> # 開啓使用最新版本軟件包
- 使用
pkgs --update
命令下載軟件包 - 編譯下載
特別注意:如果要開啓TLS加密功能,編譯時會依賴mebtls服務,主要的兩個文件tls_client.c/tls_client.h.如果只是簡單的從移植webclient和mbedtls兩個包是不會有這兩個文件的,所以要採取RTT ENV的方式先獲取.當然啦,如果你直接玩RTT,那就按照官網操作吧.
3.啓動例程
本例程使用的測試網站是 RT-Thread 系統的官方網站。GET 請求示例可以從網站中獲取並打印顯示文件內容;POST 請求示例可以上傳數據到測試網站,測試網站會響應相同的數據。
HTTP 收發數據包括頭部數據和正文數據兩部分,以下稱頭部數據爲
header 數據
,正文數據爲body 數據
。
3.1GET 請求示例
GET 請求示例流程:
- 創建 client 會話結構體
- client 發送 GET 請求 header 數據(使用默認header 數據)
- server 響應 header 數據和 body 數據
- 打印 server 響應 body 數據
- GET 請求測試完成/失敗
GET 請求示例使用方式有如下兩種:
- 在 MSH 中使用命令
web_get_test
執行 GET 請求示例程序,可以獲取並打印顯示默認網址下載的文件信息;在 MSH 中使用命令web_get_test -s
執行 POST 請求示例程序,使用簡化接口(webclient_request 接口)發送 GET請求,適用於簡短數據的收發。如下圖 LOG 顯示:
msh />web_get_test
webclient get response data:
RT-Thread is an open source IoT operating system from China, which has strong scalability: from a tiny kernel running on a tiny core, for example ARM Cortex-M0, or Cortex-M3/4/7, to a rich feature system running on MIPS32, ARM Cortex-A8, ARM Cortex-A9 DualCore etc.
msh />web_get_test -s
webclient send get request by simplify request interface.
webclient get response data:
RT-Thread is an open source IoT operating system from China, which has strong scalability: from a tiny kernel running on a tiny core, for example ARM Cortex-M0, or Cortex-M3/4/7, to a rich feature system running on MIPS32, ARM Cortex-A8, ARM Cortex-A9 DualCore etc.
msh />
- 在 MSH 中使用命令
web_get_test [URI]
或web_get_test -s [URI]
格式命令執行 GET 請求示例程序,其中 URI 爲用戶自定義的支持 GET 請求的地址。
3.2POST 請求示例
POST 請求示例流程如下:
- 創建 client 會話結構體
- 拼接 POST 請求需要的 header 數據
- client 發送拼接的 header 數據和 body 數據
- server 響應 header 數據和 body 數據
- 打印 server 響應 body 數據
- POST 請求測試完成/失敗
POST 請求示例使用方式有如下兩種:
- 在 MSH 中使用命令
web_post_test
執行 POST 請求示例程序,可以獲取並打印顯示響應數據(默認 POST 請求的地址是類似於回顯的地址,會返回上傳的數據);在 MSH 中使用命令web_post_test -s
執行 POST 請求示例程序,使用簡化接口(webclient_request 接口)發送 POST 請求,適用於簡短數據的收發。如下圖 LOG 顯示:
msh />web_post_test
webclient post response data :
RT-Thread is an open source IoT operating system from China!
msh />
msh />web_post_test -s
webclient send post request by simplify request interface.
webclient post response data:
RT-Thread is an open source IoT operating system from China!
msh />
- 在 MSH 中使用命令
web_post_test [URI]
或者web_post_test -s [URI]
格式命令執行 POST 請求示例程序,其中 URI 爲用戶自定義的支持 POST 請求的地址。