问题背景

小组使用C++开发,使用libcurl封装了Http请求模块。由于项目需求实现gzip压缩,便通过libcurl压缩选项实现了该功能。当开启gzip压缩后,短时间内多次发送Http请求,会出现报错“Send failed since rewinding of the data stream failed”。

问题原因

通过开启debug选项,排查到问题是连接意外断开,当libcurl尝试重新上传数据时,调用自定义的函数 CURLOPT_READFUNCTION, 无法找到原始数据就报错了。

解决措施

  1. 判断code码,当需要重新上传时,重置数据指针:
m_sendLength = 0
  1. 确保设置了自定义读取函数和数据
curl_easy_setopt(m_handle, CURLOPT_READFUNCTION, read_callback); curl_easy_setopt(m_handle, CURLOPT_READDATA, this);
  1. 重新发送数据
curl_easy_perform

示例:

int retryCount = 0;
const int maxRetryCount = 3; // 假设最大重试次数为3
CURLcode res;

do {
    // 重置发送数据的指针
    m_sendLength = 0;
    
    // 重置其他必要的状态,如读取/写入缓冲区

    // 执行CURL请求
    res = curl_easy_perform(m_handle);

    // 根据需要检查特定的错误代码来决定是否重试
    if (res == CURLE_OK) {
        break; // 请求成功,跳出循环
    } else {
        // 处理错误,退出循环/重试
    }

    retryCount++;
} while (retryCount < maxRetryCount);