自学内容网 自学内容网

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

场景介绍

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

使用示例

  1. CPP侧导入模块。
#include "RemoteCommunicationKit/rcp.h"
#include <stdio.h>
#include <unistd.h>
  1. CMakeLists.txt中添加以下lib。

    librcp_c.so
    
  2. 创建会话,会话发起head请求。“http://www.example.com”请根据实际情况替换为想要请求的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
}

原文地址:https://blog.csdn.net/m0_70748845/article/details/142950598

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!