libcurl

1.下载使用

官方example地址:http://curl.haxx.se/libcurl/c/fopen.html

static size_t downLoadPackage(void *ptr, size_t size, size_t nmemb, void *userdata)
{
    FILE *fp = (FILE*)userdata;
    //要写入数据地址、写入内容的单字节数size:1、size个数、文件指针: 返回的written==nmemb
    size_t written = fwrite(ptr, size, nmemb, fp);
    return written;
}

static int progressFunc(void *ptr, double totalToDownload, double nowDownloaded, double totalToUpLoad, double nowUpLoaded)
{
    CCLOG("downloading... %d%%", (int)(nowDownloaded/totalToDownload*100));
    return 0;
}

bool MyDownload::downLoad()
{
    string outFileName = _storagePath + TEMP_PACKAGE_FILE_NAME;                                     //存放文件地址
    FILE *fp = fopen(outFileName.c_str(), "wb");
    if (! fp)
    {
        CCLOG("can not create file %s", outFileName.c_str());
        return false;
    }
    /*
    下载必须的设置,带有进度条:
        出错对应的enum、初始化
        下载回调函数:
                                要写入数据地址、写入内容的单字节数size:1、size个数(总的size个数数文件大小)、文件指针: 返回的written==nmemb
                                static size_t downLoadPackage(void *ptr, size_t size, size_t nmemb, void *userdata)、
        必须有、
        指向写入文件的指针,如果是string则&_version地址、
        设置成false、
        显示下载进度或上传进度:
                                static int progressFunc(void *ptr, double totalToDownload, double nowDownloaded, double totalToUpLoad, double nowUpLoaded)、
        执行、清理
        失败、下载成功
     
     错误:
        没有初始化 失败:CURLcode res  43
        CURLOPT_SSL_VERIFYPEER没有CURLcode res报错 60
        执行时错误 1 可能下载地址有错
     */
    CURLcode res;
    _curl = curl_easy_init();
    res = curl_easy_setopt(_curl, CURLOPT_URL, _packageUrl.c_str());
    res = curl_easy_setopt(_curl, CURLOPT_WRITEFUNCTION, downLoadPackage);
    res = curl_easy_setopt(_curl, CURLOPT_SSL_VERIFYPEER, 0L);
    res = curl_easy_setopt(_curl, CURLOPT_WRITEDATA, fp);
    res = curl_easy_setopt(_curl, CURLOPT_NOPROGRESS, false);
    res = curl_easy_setopt(_curl, CURLOPT_PROGRESSFUNCTION, progressFunc);
    res = curl_easy_perform(_curl);                                                                                         
    curl_easy_cleanup(_curl);
    
    if (res != 0)
    {
        CCLOG("error when download package");
        fclose(fp);
        return false;
    }
    
    CCLOG("succeed downloading package %s", _packageUrl.c_str());
    
    fclose(fp);
    return true;
}


//获取下载信息、连接时间、错误信息

curl_easy_getinfo(curl,CURLINFO_RESPONSE_CODE, responseCode);//int32_t *responseCode

curl_easy_setopt(handle,CURLOPT_TIMEOUT,int32_t 类型);  //CURL *handle

curl_easy_setopt(handle,CURLOPT_TIMEOUT, int32_t 类型);

curl_easy_setopt(handle,CURLOPT_ERRORBUFFER, errorBuffer);//staticchar errorBuffer[256];


断点下载

curl_easy_setopt(curl, CURLOPT_RANGE, b.c_str()) // b已经完成多少字节

size_t writeFile(void *ptr, size_t size, size_t nmemb, void *stream)  //b是nmemb的 不断累加




















你可能感兴趣的:(libcurl)