You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用C++ libcurl调用Dropbox API获取文件元数据返回HTTP 400错误

解决Dropbox API获取文件元数据时的HTTP 400错误

问题根源

你的代码里有两个关键错误导致400响应:

  1. Content-Type请求头格式错误
    代码中添加Content-Type头时错误地包含了额外的双引号:

    headers = curl_slist_append(headers, "\"Content-Type\":\"application/json\"");
    

    这会让服务器收到的头变成"Content-Type":"application/json",而非正确的Content-Type: application/json,导致服务器无法识别请求体格式。

  2. POST数据长度设置错误
    你手动设置了CURLOPT_POSTFIELDSIZE为30L,但实际请求体{"path":"/3.png"}的长度是17字节。错误的长度会让服务器解析请求体时出错,触发400错误。

修正后的代码

std::ostringstream stream;
curl_slist* headers = NULL;

CURL* curl = curl_easy_init();
if (!curl) {
    return 0;
}

// 构造请求体
const std::string post_data = R"({"path":"/3.png"})";

// 设置API地址
curl_easy_setopt(curl, CURLOPT_URL, "https://api.dropboxapi.com/2/files/get_metadata");

// 添加正确的请求头
headers = curl_slist_append(headers, "Authorization: <MY TOKEN>");
headers = curl_slist_append(headers, "Content-Type: application/json");
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);

// 设置回调和数据存储
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &stream);

// 设置POST请求
curl_easy_setopt(curl, CURLOPT_POST, 1L);
// 直接传入字符串,让libcurl自动计算长度(移除错误的POSTFIELDSIZE设置)
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, post_data.c_str());

CURLcode res = curl_easy_perform(curl);
if (res != CURLE_OK) {
    curl_slist_free_all(headers);
    curl_easy_cleanup(curl);
    return 0;
}

// 获取响应结果
std::string output = stream.str();

// 清理资源
curl_slist_free_all(headers);
curl_easy_cleanup(curl);

修改说明

  • 移除了Content-Type头中的多余双引号,确保头格式符合HTTP规范。
  • 删除了CURLOPT_POSTFIELDSIZE设置,让libcurl自动计算POST数据的长度,避免手动计算错误。
  • 添加了curl初始化的空指针检查,以及资源清理的容错处理(即使请求失败也会释放headers和curl句柄)。
  • 使用std::string存储请求体,避免char数组的长度限制问题。

内容的提问来源于stack exchange,提问作者Pandorax

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 12:40:21