0

我正在使用 C++ 和 libcurl 来制作 Web Spider。我遇到了一个问题,当我使用队列获取 URL 时,我收到一条错误消息,指出不支持 HTTP。错误是:http://google.com* Protocol "http not supported or disabled in libcurl* Unsupported protocol。这是我的代码:

#include <iostream>
#include <queue>
#include <curl/curl.h>

std::string data; //will hold the url's contents

size_t writeCallback(char* buf, size_t size, size_t nmemb, void* up)
{ //callback must have this declaration
    //buf is a pointer to the data that curl has for us
    //size*nmemb is the size of the buffer

    for (int c = 0; c<size*nmemb; c++)
    {
        data.push_back(buf[c]);
    }
    return size*nmemb; //tell curl how many bytes we handled
}


int main(int argc, const char * argv[])
{
    std::queue<std::string> Q;
    Q.push("http://google.com");

    while (!Q.empty()) {
        std::string url = Q.front();
        std::cout << Q.front();
        CURL* curl; //our curl object

        curl_global_init(CURL_GLOBAL_ALL); //pretty obvious
        curl = curl_easy_init();

        curl_easy_setopt(curl, CURLOPT_URL, &url);
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, &writeCallback);
        curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L); //tell curl to output its progress

        curl_easy_perform(curl);

        std::cout << std::endl << data << std::endl;
        std::cin.get();

        curl_easy_cleanup(curl);
        curl_global_cleanup();
        data.erase();
        Q.pop();
    }

    return 0;
}

我是 C++ 新手。我应该朝哪个方向寻找解决方法?

4

2 回答 2

3

这是错误的:

curl_easy_setopt(curl, CURLOPT_URL, &url);

这是正确的:

curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
于 2013-01-01T21:50:08.523 回答
3

std::string不是char*。你不能说

curl_easy_setopt(curl, CURLOPT_URL, &url);

因为这std::string*是作为一个选项而不是char*. 正确的方法是

curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
于 2013-01-01T21:51:04.173 回答