概念先知道
- POST:HTTP 方法之一,表示“把数据提交给服务器”,常用于表单提交、上报传感器数据、创建资源。
- 请求体(Body):POST 与 GET 的主要区别——数据放在请求体里而不是 URL 里,适合较长的数据。
- chunked(分块传输):不确定总长度时,把数据切成多个“块”,每块前面写十六进制长度,最后以
0\r\n\r\n结束。例程的payload_cb就演示了这种编码。 - 响应回调:服务器返回的数据通过
response_cb回调逐段打印。
例程功能简介
本页对应博流官方 SDK 的 wifi_http 例程(examples/wifi/sta/wifi_http),其中 POST 部分(wifi_http_client.c):
wifi_http_test <url>在 GET 完成后继续构造 POST 请求;req.method = HTTP_POST,并设置header_fields为Transfer-Encoding: chunked;payload_cb回调在发送请求时被调用,按 chunked 格式写入三段内容并返回长度;- 调用
https_client_request(&req, 3*1000, "IPv4 POST")同步等待响应。 - 同族例程:PUT/DELETE 无现成例程,教程提供自编 PUT、自编 DELETE示例;GET 见 HTTP GET 页。
操作步骤
在终端进入 SDK 的 HTTP 例程目录(前提:环境已按快速开始(Linux)或Windows搭好):
cd examples/wifi/sta/wifi_http统一填写 bl616:
make CHIP=bl616 BOARD=bl616dk按住 BOOT 键短按 EN/RST 进入下载模式后烧录:
make flash CHIP=bl616 COMX=/dev/ttyUSB0串口助手波特率 2000000,看到 bouffalolab /> 后连接路由器,再执行命令(例程先 GET 再 POST,本页关注 POST 部分):
wifi_sta_connect Your_SSID 12345678
wifi_http_test http://www.gov.cnGET 之后例程继续执行 POST,打印 Http client POST request server success。POST 请求体采用 chunked(分块)编码,依次发送 foobar、chunked、last 三段并附长度前缀。
代码执行流程
HTTP POST 从请求到响应的完整流程如下:
例程调用的 API 介绍
https_client_request(&req, timeout, user_data)
同步发起一次 HTTP/HTTPS 请求。POST 时 req.method = HTTP_POST,req.header_fields 可附加自定义头。
参数:
&req:struct https_client_requesttimeout:超时毫秒数(例程 3000)user_data:透传数据
返回值:>= 0 成功;< 0 失败
payload_cb(sock, req, user_data)
发送请求体的回调:需要发送数据时由库调用,示例按 chunked 格式把三段内容(带长度前缀)写入 socket,返回本次发送的字节数。
参数:
sock:连接 socketreq:struct http_requestuser_data:用户数据
返回值:实际写入的字节数
response_cb(rsp, final_data, user_data)
响应回调,逐段打印服务器返回的数据。
参数:
rsp:struct http_response,含recv_buf与data_lenfinal_data:HTTP_DATA_MORE/HTTP_DATA_FINALuser_data:用户数据
返回值:无
完整代码
以下为 wifi_http_client.c 完整源码,与官方示例(examples/wifi/sta/wifi_http)一致,默认折叠,点击展开:
📜 点击展开 wifi_http/main.c 完整代码
/****************************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership. The
* ASF licenses this file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*
****************************************************************************/
/****************************************************************************
* Included Files
****************************************************************************/
#include "FreeRTOS.h"
#include "task.h"
#include "timers.h"
#include <lwip/tcpip.h>
#include <lwip/sockets.h>
#include <lwip/netdb.h>
#include "wifi_mgmr_ext.h"
#include "bflb_irq.h"
#include "bflb_uart.h"
#include "rfparam_adapter.h"
#include "board.h"
#include "shell.h"
#ifndef BL602
#include "fhost_api.h"
#include "wifi_mgmr.h"
#endif
#include "async_event.h"
#include "mm.h"
#define DBG_TAG "MAIN"
#include "log.h"
struct bflb_device_s *gpio;
/****************************************************************************
* Pre-processor Definitions
****************************************************************************/
#define WIFI_STACK_SIZE (1536)
#define TASK_PRIORITY_FW (16)
/****************************************************************************
* Private Types
****************************************************************************/
/****************************************************************************
* Private Data
****************************************************************************/
static struct bflb_device_s *uart0;
extern void shell_init_with_task(struct bflb_device_s *shell);
extern void wifi_event_handler(async_input_event_t ev, void *priv);
/* Main wifi stack entry point */
extern void wifi_main(void *param);
#ifdef BL602
extern void wifi_task_create(void);
extern int fhost_init(void);
extern int wifi_mgmr_task_start(void);
#endif
/****************************************************************************
* Private Function Prototypes
****************************************************************************/
/****************************************************************************
* Functions
****************************************************************************/
void wifi_start_firmware_task(void *param)
{
LOG_I("Starting wifi ...\r\n");
async_register_event_filter(EV_WIFI, wifi_event_handler, NULL);
wifi_task_create();
LOG_I("Starting fhost ...\r\n");
fhost_init();
vTaskDelete(NULL);
}
void wifi_event_handler(async_input_event_t ev, void *priv)
{
uint32_t code = ev->code;
switch (code) {
case CODE_WIFI_ON_INIT_DONE: {
LOG_I("[APP] [EVT] %s, CODE_WIFI_ON_INIT_DONE\r\n", __func__);
wifi_mgmr_task_start();
} break;
case CODE_WIFI_ON_MGMR_DONE: {
LOG_I("[APP] [EVT] %s, CODE_WIFI_ON_MGMR_DONE\r\n", __func__);
} break;
case CODE_WIFI_ON_SCAN_DONE: {
LOG_I("[APP] [EVT] %s, CODE_WIFI_ON_SCAN_DONE\r\n", __func__);
wifi_mgmr_sta_scanlist();
} break;
case CODE_WIFI_ON_CONNECTED: {
LOG_I("[APP] [EVT] %s, CODE_WIFI_ON_CONNECTED\r\n", __func__);
void mm_sec_keydump();
mm_sec_keydump();
} break;
case CODE_WIFI_ON_GOT_IP: {
LOG_I("[APP] [EVT] %s, CODE_WIFI_ON_GOT_IP\r\n", __func__);
LOG_I("[SYS] Memory left is %d Bytes\r\n", kfree_size(0));
} break;
case CODE_WIFI_ON_DISCONNECT: {
LOG_I("[APP] [EVT] %s, CODE_WIFI_ON_DISCONNECT\r\n", __func__);
} break;
case CODE_WIFI_ON_AP_STARTED: {
LOG_I("[APP] [EVT] %s, CODE_WIFI_ON_AP_STARTED\r\n", __func__);
} break;
case CODE_WIFI_ON_AP_STOPPED: {
LOG_I("[APP] [EVT] %s, CODE_WIFI_ON_AP_STOPPED\r\n", __func__);
} break;
case CODE_WIFI_ON_AP_STA_ADD: {
LOG_I("[APP] [EVT] [AP] [ADD] %lld\r\n", xTaskGetTickCount());
} break;
case CODE_WIFI_ON_AP_STA_DEL: {
LOG_I("[APP] [EVT] [AP] [DEL] %lld\r\n", xTaskGetTickCount());
} break;
default: {
LOG_I("[APP] [EVT] Unknown code %u \r\n", code);
}
}
}
int main(void)
{
board_init();
uart0 = bflb_device_get_by_name("uart0");
shell_init_with_task(uart0);
if (0 != rfparam_init(0, NULL, 0)) {
LOG_I("PHY RF init failed!\r\n");
return 0;
}
LOG_I("PHY RF init success!\r\n");
tcpip_init(NULL, NULL);
xTaskCreate(wifi_start_firmware_task, "wifi init", 1024, NULL, 10, NULL);
vTaskStartScheduler();
while (1) {
}
}
int cmd_gethostbyname(int argc, char **argv)
{
struct addrinfo hints, *res, *p;
int status;
char ipstr[INET6_ADDRSTRLEN];
char *name = argv[1];
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
if(!strcmp(argv[1], "-4")) {
hints.ai_family = AF_INET;
name = argv[2];
}
if(!strcmp(argv[1], "-6")) {
hints.ai_family = AF_INET6;
name = argv[2];
}
hints.ai_socktype = SOCK_STREAM;
if ((status = getaddrinfo(name, NULL, &hints, &res)) != 0) {
fprintf(stderr, "getaddrinfo error: %d\r\n", status);
return 0;
}
printf("IP addresses for %s:\r\n", name);
for (p = res; p != NULL; p = p->ai_next) {
void *addr;
char *ipver;
if (p->ai_family == AF_INET) {
struct sockaddr_in *ipv4 = (struct sockaddr_in *)p->ai_addr;
addr = &(ipv4->sin_addr);
ipver = "IPv4";
} else {
struct sockaddr_in6 *ipv6 = (struct sockaddr_in6 *)p->ai_addr;
addr = &(ipv6->sin6_addr);
ipver = "IPv6";
}
inet_ntop(p->ai_family, addr, ipstr, sizeof ipstr);
printf(" %s: %s\r\n", ipver, ipstr);
}
freeaddrinfo(res);
return 0;
}
SHELL_CMD_EXPORT_ALIAS(cmd_gethostbyname, gethostbyname, gethostbyname command);📜 点击展开 wifi_http_client.c 完整代码
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/socket.h>
#include <lwip/api.h>
#include <lwip/arch.h>
#include <lwip/opt.h>
#include <lwip/inet.h>
#include <lwip/errno.h>
#include <netdb.h>
#include "shell.h"
#include "utils_getopt.h"
#include "bflb_mtimer.h"
#include "https_client.h"
#ifndef ARRAY_SIZE
#define ARRAY_SIZE(array) (sizeof(array) / sizeof((array)[0]))
#endif
static int payload_cb(int sock, struct http_request *req, void *user_data)
{
const char *content[] = {
"foobar",
"chunked",
"last"
};
char tmp[64];
int i, pos = 0;
for (i = 0; i < ARRAY_SIZE(content); i++) {
pos += snprintf(tmp + pos, sizeof(tmp) - pos,
"%x\r\n%s\r\n",
(unsigned int)strlen(content[i]),
content[i]);
}
pos += snprintf(tmp + pos, sizeof(tmp) - pos, "0\r\n\r\n");
(void)zsock_send(sock, tmp, pos, 0);
return pos;
}
static int log_output(void *ptr, size_t size)
{
size_t i;
for (i = 0; i < size; i++) {
putchar(((char *)ptr)[i]);
}
return i;
}
static void response_cb(struct http_response *rsp,
enum http_final_call final_data,
void *user_data)
{
log_output(rsp->recv_buf, rsp->data_len);
if (final_data == HTTP_DATA_MORE) {
//printf("Partial data received (%zd bytes)\r\n", rsp->data_len);
} else if (final_data == HTTP_DATA_FINAL) {
//printf("All the data received (%zd bytes)\r\n", rsp->data_len);
}
}
#define PING_USAGE \
"wifi_http_test [url]\r\n" \
"\t url: url or dest server ip\r\n" \
static void wifi_test_http_client_init(int argc, char **argv)
{
int ret;
char *url;
struct https_client_request req;
if (argc < 2) {
printf("%s", PING_USAGE);
return;
}
/* get address (argv[1] if present) */
url = argv[1];
memset(&req, 0, sizeof(req));
req.method = HTTP_GET;
req.url = url;
req.protocol = "HTTP/1.1";
req.response = response_cb;
ret = https_client_request(&req, 3*1000, "IPv4 GET");
if (ret < 0) {
printf("http_client get request fail ret:%d\r\n", ret);
} else {
printf("Http client GET request server success\r\n");
}
const char *headers[] = {
"Transfer-Encoding: chunked\r\n",
NULL
};
memset(&req, 0, sizeof(req));
req.method = HTTP_POST;
req.url = url;
req.protocol = "HTTP/1.1";
req.payload_cb = payload_cb;
req.header_fields = headers;
req.response = response_cb;
ret = https_client_request(&req, 3*1000, "IPv4 POST");
if (ret < 0) {
printf("http_client post request fail ret:%d\r\n", ret);
} else {
printf("Http client POST request server success\r\n");
}
}
#ifdef CONFIG_SHELL
#include <shell.h>
int cmd_wifi_http_client(int argc, char **argv)
{
wifi_test_http_client_init(argc, argv);
return 0;
}
SHELL_CMD_EXPORT_ALIAS(cmd_wifi_http_client, wifi_http_test, wifi http client test);
#endifFAQ
POST 请求失败
确认服务器支持 POST 且 URL 正确;chunked 编码需要服务器支持 Transfer-Encoding: chunked(多数 Web 服务器都支持);本地测试可在电脑上跑 python3 -m http.server 之类带 POST 处理的服务。
如何发送 JSON 而不是固定三段文本
在 payload_cb 里把 content[] 换成你的 JSON 字符串即可;也可以不用 chunked,直接在 req.payload / req.payload_len 里填完整内容(参考本栏目的自编 PUT 示例)。
遇到问题?
如有其他问题,请到统一的提问与讨论区:Ai-Thinker Discussions

