• libcurl下载文件


    一、初始化

    CURL *pHandler = curl_easy_init();

     

    二、设置请求参数;

    调用curl_easy_setopt方法,设置选项

    curl_easy_setopt(pHandler , CURLOPT_WRITEFUNCTION, WriteData);

    curl_easy_setopt(pHandler , CURLOPT_WRITEDATA, pFile);

     

    //设置请求的url地址

    curl_easy_setopt(pHandler , CURLOPT_URL, strUrl.c_str());

    //如果为post请求,这里设置提交的参数

    //curl_easy_setopt(pHandler , CURLOPT_POSTFIELDS, strPostData.c_str());

    curl_easy_setopt(pHandler , CURLOPT_FAILONERROR, true);
    curl_easy_setopt(pHandler , CURLOPT_TIMEOUT, 60);  //超时时间(秒)
    curl_easy_setopt(pHandler , CURLOPT_NOSIGNAL, true);

     

    三、执行下载

    CURLcode codeRet = curl_easy_perform(pHandler);

     

    四、获取返回的http状态码

    long retcode = 0;

    curl_easy_getinfo(pHandler, CURLINFO_RESPONSE_CODE , &retcode);

     

    五、清理

    curl_easy_cleanup(pHandler);

     

    if (codeRet == CURLE_OK && (retcode == 200 || retcode == 304 || retcode == 204))

    {

    //下载成功

    }

    else

    {

    //下载失败

    }

     

    size_t WriteData(const char *ptr, size_t size, size_t nmemb, FILE *stream)
    {
        if (!ptr || !stream)
        {
            return 0;
        }


        return fwrite(ptr, size, nmemb, stream);
    }

     

    关于文件的读写操作,可以参考这里:

    fopen

    fseek

    ftell

    fread

    fwrite

  • 相关阅读:
    MySQL链接超时的解决办法
    使用Axis开发Web Service程序
    Linux动态库(.so)搜索路径
    MYSQL性能调优简述
    什么是AXIS
    巧夺天工的kfifo
    双离合DSG
    实例讲解C# WebService
    如何为 MySQL 选择更合适的服务器硬件
    7 MySQL 事务与锁定命令
  • 原文地址:https://www.cnblogs.com/meteoric_cry/p/3681546.html
Copyright © 2020-2023  润新知