鸿蒙开发(NEXT/API 12)【使用head发送网络请求 (C/C++)】远场通信服务

场景介绍

发送一个带有默认HTTP参数的HTTP HEAD请求,并返回来自服务器的HTTP响应。使用异步回调。类似GET请求,但只返回相应头,不返回实体内容。可以获取资源的元信息,如文件大小、修改日期等。

使用示例

  1. CPP侧导入模块。

    #include "RemoteCommunicationKit/rcp.h"#include <stdio.h>#include <unistd.h>
    
  2. CMakeLists.txt中添加以下lib。

    librcp_c.so
    
  3. 创建会话,会话发起head请求。 请根据实际情况替换为想要请求的URL地址。等待响应返回后,销毁request并关闭session。

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);
    }
}
bool g_callback = false;

int main() {
    const char *kHttpServerAddress = "http://www.example.com/head";
    Rcp_Request *request = HMS_Rcp_CreateRequest(kHttpServerAddress);
    request->method = RCP_METHOD_HEAD;
    uint32_t errCode = 0;
    // 创建session
    Rcp_Session *session = HMS_Rcp_CreateSession(NULL, &errCode);
    // 配置请求回调
    Rcp_ResponseCallbackObject responseCallback = {ResponseCallback, NULL};
    // 发起fetch请求
    errCode = HMS_Rcp_Fetch(session, request, &responseCallback);
    // 等待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
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值