鸿蒙开发(NEXT/API 12)【使用fetch发起异步网络请求】远场通信服务
·
场景介绍
发送一个异步HTTP请求,也可以设置请求头和请求体等参数,并返回来自服务器的HTTP响应。常用于获取资源,支持通过拦截器来处理请求和响应。
接口说明
| 接口名 | 描述 |
|---|---|
| uint32_t HMS_Rcp_Fetch(Rcp_Session *session, Rcp_Request *request, const Rcp_ResponseCallbackObject *responseCallback); | 发送一个HTTP请求,并返回来自服务器的HTTP响应。使用responseCallback异步回调。 |
- CPP侧导入模块。
#include "RemoteCommunicationKit/rcp.h"
#include <stdio.h>
#include <unistd.h>
-
CMakeLists.txt中添加以下lib。
librcp_c.so -
创建Request对象。"https://www.example.com"请根据实际情况替换为想要请求的URL地址。(完整见步骤5)
const char *kHttpServerAddress = "http://www.example.com";
Rcp_Request *request = HMS_Rcp_CreateRequest(kHttpServerAddress);
- 创建会话。(完整见步骤5)
uint32_t errCode = 0;
Rcp_Session *session = HMS_Rcp_CreateSession(NULL, &errCode);
- 发起请求,并处理返回结果。最后关闭session。
bool g_callback = false;
// 异步请求的响应处理回调,请用户自定义
void ResponseCallback(void *usrCtx, Rcp_Response *response, uint32_t errCode)
{
(void *)usrCtx;
if (response != NULL) {
printf("Response status: %d\n", response->statusCode);
} else {
printf("Fetch failed: errCode: %u\n", errCode);
}
// 注意清理响应
if (response != NULL) {
response->destroyResponse(response);
}
g_callback = true;
}
int main() {
const char *kHttpServerAddress = "http://www.example.com";
Rcp_Request *request = HMS_Rcp_CreateRequest(kHttpServerAddress);
request->method = RCP_METHOD_GET;
uint32_t errCode = 0;
// 创建session
Rcp_Session *session = HMS_Rcp_CreateSession(NULL, &errCode);
// 配置请求回调
Rcp_ResponseCallbackObject responseCallback = {ResponseCallback, NULL};
// 发起请求
errCode = HMS_Rcp_Fetch(session, request, &responseCallback);
// 处理errCode
// 等待fetch结果
int timeout = 100;
while (timeout-- > 0 && !g_callback) {
usleep(1000);
}
// 在退出前取消可能还在执行的requests
errCode = HMS_Rcp_CancelSession(session);
// 清理request
HMS_Rcp_DestroyRequest(request);
// 关闭session
errCode = HMS_Rcp_CloseSession(&session);
// 处理errCode
return 0;
}
更多推荐



所有评论(0)