簡體   English   中英

libcurl WriteMemoryCallback方法在iOS上不起作用

[英]libcurl WriteMemoryCallback method don't work on iOS

我使用libcurl向服務器請求數據。但是WriteMemoryCallback方法無法成功工作。 我的操作系統是iOS,libcurl的版本是7.40.0。 這些是我的代碼:

struct ResultStruct {
    char *memory;
    char *cookie_list;
    char *session_id;
};

struct MemoryStruct {
    char *memory;
    size_t size;
};

static size_t WriteMemoryCallback(char *contents, size_t size, size_t nmemb, struct MemoryStruct *userp)
{
    size_t realsize = size * nmemb;
    userp->memory = contents;
    if(userp->memory == NULL) {
        /* out of memory! */
        printf("not enough memory (realloc returned NULL)\n");
        return 0;
    }
    return realsize;
}

curl_slist * get_cookies(CURL *curl)
{
    CURLcode res;
    struct curl_slist *cookies;
    printf("Cookies, curl knows:\n");
    res = curl_easy_getinfo(curl, CURLINFO_COOKIELIST, &cookies);
    if (res != CURLE_OK) {
        fprintf(stderr, "Curl curl_easy_getinfo failed: %s\n", curl_easy_strerror(res));
        exit(1);
    }
    return cookies;
}

char *get_comment(char *url)
{
    CURL *curl;
    CURLcode res;
    struct MemoryStruct *chunk = new struct MemoryStruct;
    chunk->memory = new char[2000];
    curl_global_init(CURL_GLOBAL_ALL);
    curl = curl_easy_init();
    if(curl) {
        curl_easy_setopt(curl, CURLOPT_URL, url);
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, chunk);
        curl_easy_setopt(curl, CURLOPT_COOKIEFILE, "");
        curl_easy_setopt(curl, CURLOPT_USERAGENT, "libcurl-agent/1.0");
        curl_easy_setopt(curl, CURLOPT_TIMEOUT, 10);
        res = curl_easy_perform(curl);
        if(res != CURLE_OK)
            fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res));
        curl_easy_cleanup(curl);
    }
//    curl_global_cleanup();
    std::cout << "------------------------------------------" << std::endl;
    std::cout << chunk->memory << std::endl;
    char *result = new char[2000];
    result = chunk->memory;
//    delete chunk->memory;
    delete chunk;
    std::cout << "******************************************" << std::endl;
    std::cout << result << std::endl;
    std::cout << "------------------------------------------" << std::endl;
    return result;
}

我在方法WriteMemoryCallback中設置了一個斷點,並且發現參數內容包含我需要的數據。 但是我在get_comment方法中設置了一個斷點,我發現參數塊丟失了一些數據。 我不知道如何解決該錯誤。找不到該錯誤。我需要幫助。

我強烈建議您在iOS上使用NSURLSession而不是libcurl

但是,這里的問題是,隨着libcurl接收數據,多次調用WriteMemoryCallback。 您應該匯總從這些多次調用中收到的數據,但是您沒有這樣做,您只是將userp->memory設置為指向contents (這是一個壞主意,因為您至少應該復制它,回調返回后, contents不保證仍包含相關數據。

您需要分配內存並將新接收的數據附加到WriteMemoryCallback

或使用NSURLSessiondataTaskWithURL:completionHandler將為您dataTaskWithURL:completionHandler所有這些工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM