HarmonyOS 鸿蒙Next 如何使用HMS_Rcp_FetchSync c++实现https长连接请求

HarmonyOS 鸿蒙Next 如何使用HMS_Rcp_FetchSync c++实现https长连接请求

使用 HMS_Rcp_CreateSession(NULL, &errCode);

创建一个全局session,然后

Rcp_Request * request = HMS_Rcp_CreateRequest(kHttpServerAddressAuth);
Rcp_Headers* header = HMS_Rcp_CreateHeaders();
// 初始化headers数据
uint32_t error = HMS_Rcp_SetHeaderValue(header, "Connection", "keep-alive");
HMS_Rcp_SetHeaderValue(header, "Content-Type", "application/json");

Rcp_Configuration config{};
request->configuration = &config;
config.transferConfiguration.timeout.connectMs=REQUEST_TIMEOUT;

Rcp_RequestContent requestContent;
requestContent.type= RCP_CONTENT_TYPE_STRING;
requestContent.data.contentStr.buffer=str;
requestContent.data.contentStr.length=strlen(str);

request->content=&requestContent;
request->method=RCP_METHOD_POST;
request->headers=header;

uint32_t errCode = 0;

Rcp_Response *response = HMS_Rcp_FetchSync(session, request, &errCode);

发起两次http请求,抓包发现每次请求的客户端端口都不一样,也就是说就算加上keep-alive 还是每次请求会关闭连接,是不是我使用有问题?有没有办法保证两次请求都是用一个客户端端口的长连接模式使用HMS_Rcp_FetchSync?或者使用鸿蒙其他c接口发起http请求


更多关于HarmonyOS 鸿蒙Next 如何使用HMS_Rcp_FetchSync c++实现https长连接请求的实战教程也可以访问 https://www.itying.com/category-93-b0.html

2 回复

通过抓包发现HMS_Rcp_FetchSync底层是通过curl实现的交互,于是交叉编译出libcrypto.a,libcurl.a,libssl.a自己实现了长连

编译方法参考的下面的文章,我下载的不是ndk,是linux的命令行工具,包含了ndk

https://developer.huawei.com/consumer/cn/download/command-line-tools-for-hmos

,路径稍有不同

https://blog.csdn.net/jwybobo2007/article/details/142880711

使用方法参考:

https://developer.huawei.com/consumer/cn/doc/harmonyos-faqs-V5/faqs-ndk-31-V5

更多关于HarmonyOS 鸿蒙Next 如何使用HMS_Rcp_FetchSync c++实现https长连接请求的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在HarmonyOS鸿蒙Next中,使用HMS_Rcp_FetchSync实现HTTPS长连接请求,可以通过以下步骤进行:

  1. 引入头文件:首先需要引入相关的头文件,包括HMS_Rcp_FetchSync的头文件以及其他必要的依赖。

    #include <hms_rcp_fetch_sync.h>
    #include <string>
    
  2. 初始化HMS_Rcp_FetchSync:在使用HMS_Rcp_FetchSync之前,需要进行初始化操作。

    hms_rcp_fetch_sync_init();
    
  3. 配置HTTPS请求:设置HTTPS请求的URL、请求方法(如GET或POST)、请求头等参数。

    std::string url = "https://example.com";
    std::string method = "GET";
    std::map<std::string, std::string> headers;
    headers["Content-Type"] = "application/json";
    
  4. 发送HTTPS请求:使用HMS_Rcp_FetchSync发送HTTPS请求,并获取响应结果。

    hms_rcp_fetch_sync_request_t request;
    request.url = url.c_str();
    request.method = method.c_str();
    request.headers = headers;
    
    hms_rcp_fetch_sync_response_t response;
    hms_rcp_fetch_sync_send_request(&request, &response);
    
  5. 处理响应:根据返回的响应结果进行处理,例如读取响应体或状态码。

    if (response.status_code == 200) {
        std::string response_body(response.body, response.body_length);
        // 处理响应体
    }
    
  6. 释放资源:在请求完成后,释放相关的资源。

    hms_rcp_fetch_sync_release_response(&response);
    hms_rcp_fetch_sync_deinit();
    
  7. 长连接维护:如果需要保持长连接,可以在一定时间间隔内重复发送请求,或者使用WebSocket等其他协议来实现长连接。

通过以上步骤,你可以在HarmonyOS鸿蒙Next中使用HMS_Rcp_FetchSync实现HTTPS长连接请求。

回到顶部