在Qt 4.8中使用C ++,libcurl获取网站源时出错

时间:2012-11-22 12:57:48

标签: c++ qt libcurl

我正在尝试使用Qt 4.8中的C ++和libcurl获取网站源代码。我是Qt和C ++的新手。 但是,我收到一条错误消息

错误消息 -

Starting C:*****.exe...
The program has unexpectedly finished.
C:*****.exe exited with code  -1073741819
#include <curl/include/curl/curl.h>
#include <fstream>
#include <sstream>
#include <iostream>


static size_t data_write(void* buf, size_t size, size_t nmemb, void* userp)
{
    if(userp)
    {
        std::ostream& os = *static_cast<std::ostream*>(userp);
        std::streamsize len = size * nmemb;
        if(os.write(static_cast<char*>(buf), len))
            return len;
    }

    return 0;
}

CURLcode curl_read(const std::string& url, std::ostream& os, long timeout = 30)
{
    CURLcode code(CURLE_FAILED_INIT);
    CURL* curl = curl_easy_init();

    if(curl)
    {
        if(CURLE_OK == (code = curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, &data_write))
        && CURLE_OK == (code = curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 1L))
        && CURLE_OK == (code = curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L))
        && CURLE_OK == (code = curl_easy_setopt(curl, CURLOPT_FILE, &os))
        && CURLE_OK == (code = curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout))
        && CURLE_OK == (code = curl_easy_setopt(curl, CURLOPT_URL, url.c_str())))
        {
            code = curl_easy_perform(curl);
        }
        curl_easy_cleanup(curl);
    }
    return code;
}

int main()
{
    curl_global_init(CURL_GLOBAL_ALL);


    if(CURLE_OK == curl_read("http://google.com", std::cout))
    {
    // Web page successfully written to standard output (console?)
    }

    curl_global_cleanup();
    return 0;
}

上面代码的问题是什么?

P.S - 以上代码不是我的。

1 个答案:

答案 0 :(得分:0)

不要使用外部库来使用Qt所拥有的内容。它有很多!

以下是关于如何获取网页来源的简单示例!

void MainWindow::on_pushButton_clicked()
{
    QNetworkAccessManager * mgr = new QNetworkAccessManager(this);
    connect(mgr,SIGNAL(finished(QNetworkReply*)),this,SLOT(onfinish(QNetworkReply*)));
    connect(mgr,SIGNAL(finished(QNetworkReply*)),mgr,SLOT(deleteLater()));

    mgr->get(QNetworkRequest(QUrl("http://www.google.com")));

}

void MainWindow::onfinish(QNetworkReply *rep)
{
    QByteArray bts = rep->readAll();
    QString str(bts);
    QMessageBox::information(this,"sal",str,"ok");

}

如果您想创建阻止功能,请查看本教程here

希望它有所帮助!