libcurl post二进制文件及GET下载文件

本文介绍使用CURL库进行图片上传及文件下载的方法。包括通过POST方式上传本地图片到指定URL,并设置请求头及参数;以及如何通过GET方式从URL下载文件到本地,涉及CURL易用接口的初始化、配置及清理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用的版本curlcurl-7.69.1

使用的easy接口

1、二进制方式POST图片

CURL *curl;
CURLcode res;
curl = curl_easy_init();
if(curl) {
  curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "POST");
  curl_easy_setopt(curl, CURLOPT_URL, "http://xxx/res_upload?company=dc&device_name=hg-0677R");
  curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
  curl_easy_setopt(curl, CURLOPT_DEFAULT_PROTOCOL, "https");
  
  struct curl_slist *headers = NULL;
  curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
  
  curl_mime *mime;
  curl_mimepart *part;
  mime = curl_mime_init(curl);
  part = curl_mime_addpart(mime);
  curl_mime_name(part, "file");
  curl_mime_filedata(part, "/D:/system/Desktop/1.png");  /* 本地文件路径 */
  part = curl_mime_addpart(mime);
  curl_easy_setopt(curl, CURLOPT_MIMEPOST, mime);
  res = curl_easy_perform(curl);
  curl_mime_free(mime);
}
curl_easy_cleanup(curl);

2、GET下载

  CURL *m_EasyCurlHandle;
  CURLcode res;
   curl_easy_cleanup(m_EasyCurlHandle);
    m_EasyCurlHandle = curl_easy_init();

    if(m_EasyCurlHandle)
    {
        if(file_path)
            m_wfd = fopen(file_path, "wb+");
        if(!m_wfd)
        {
            return false;
        }

        curl_easy_setopt(m_EasyCurlHandle, CURLOPT_CUSTOMREQUEST, "GET");
        curl_easy_setopt(m_EasyCurlHandle, CURLOPT_FOLLOWLOCATION, 1L);
        curl_easy_setopt(m_EasyCurlHandle, CURLOPT_DEFAULT_PROTOCOL, "https");
        
        struct curl_slist *headers = NULL;
       //char Auth_header[256]={0};
        //snprintf(Auth_header, 256, "Authorization:Bearer %s", m_Tocken);
       // headers = curl_slist_append(headers, Auth_header);
        curl_easy_setopt(m_EasyCurlHandle, CURLOPT_HTTPHEADER, headers);

        //curl_easy_setopt(m_EasyCurlHandle, CURLOPT_HTTPGET, 1L);   /* 发送HTTP GET请求 */
        curl_easy_setopt(m_EasyCurlHandle, CURLOPT_URL, url);      /* URL地址设置 */
        curl_easy_setopt(m_EasyCurlHandle, CURLOPT_WRITEFUNCTION, ReceiveDataCB);
        curl_easy_setopt(m_EasyCurlHandle, CURLOPT_WRITEDATA, m_wfd); /* 设置自定义指针 */

        curl_easy_setopt(m_EasyCurlHandle, CURLOPT_VERBOSE, 1);

        CURLcode res = curl_easy_perform(m_EasyCurlHandle);
        if(res != CURLE_OK)
        {
            LOG_DEBUG << "curl_easy_perform() failed: " << curl_easy_strerror(res);
        }

        curl_slist_free_all(headers);

        if(m_wfd)
        {
            fclose(m_wfd);
            m_wfd = NULL;
        }

        curl_easy_cleanup(m_EasyCurlHandle);
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值