curl PATCH更新正常但libcurl C++实现报InvalidRequest错是什么原因
问题修复说明
核心错误1:请求头Link字段不匹配
你代码中Link头的rel属性值缺少www前缀:
- 正确值(和curl命令一致):
http://www.w3.org/ns/json-ld#context - 错误代码中的值:
http://w3.org/ns/json-ld#context
NGSI-LD接口对上下文地址校验严格,地址不匹配会直接判定请求非法。
核心错误2:CURLOPT_POSTFIELDS参数类型错误
CURLOPT_POSTFIELDS是C风格接口,要求传入const char*类型的字符串指针,你直接传入了std::string对象,会导致curl读取到非法的请求体内容,服务端无法解析。
可选优化
显式设置CURLOPT_POSTFIELDSIZE指定请求体长度,避免因字符串结尾异常导致的请求体截断问题。
修正后的代码片段
json ent={ {"type","Property"}, {"value","updated successfully"} }; curl_global_init(CURL_GLOBAL_DEFAULT); std::string json_entity = ent.dump(); CURL* curl = curl_easy_init(); CURLcode result; if (curl) { // Add headers struct curl_slist *headers = NULL; headers = curl_slist_append(headers, "Content-Type: application/json"); // 修复Link头,补全www前缀 headers = curl_slist_append(headers, R"(Link: <http://context-provider:3000/data-models/ngsi-context.jsonld>; rel="http://www.w3.org/ns/json-ld#context"; type="application/ld+json")"); // Set custom headers curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); // Set URL curl_easy_setopt(curl, CURLOPT_URL, "*URL*/attrs/topicData"); // Set request type curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "PATCH"); // 修复:传入C风格字符串指针 curl_easy_setopt(curl, CURLOPT_POSTFIELDS, json_entity.c_str()); // 可选:显式指定请求体长度 curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, json_entity.size()); // Perform the request which prints to stdout result = curl_easy_perform(curl); // Error check if (result != CURLE_OK) { std::cerr << "Error during curl request: " << curl_easy_strerror(result) << std::endl; } //Free header list curl_slist_free_all(headers); curl_easy_cleanup(curl); } else { std::cerr << "Error initializing curl." << std::endl; } curl_global_cleanup();
补充:原代码缺少curl_global_cleanup()调用,建议加上避免资源泄漏
内容的提问来源于stack exchange,提问作者muda
相关产品推荐
相关产品推荐

