场景介绍
发送一个带有默认HTTP参数的HTTP HEAD请求,并返回来自服务器的HTTP响应。使用异步回调。类似GET请求,但只返回相应头,不返回实体内容。可以获取资源的元信息,如文件大小、修改日期等。
使用示例
-
CPP侧导入模块。
#include "RemoteCommunicationKit/rcp.h"#include <stdio.h>#include <unistd.h>
-
CMakeLists.txt中添加以下lib。
librcp_c.so
-
创建会话,会话发起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
}