本文介绍了在 Qt 下制作 HTTP GET的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 n00b 问题,我似乎无法从我的 Qt 代码发出 HTTP GET 请求...

I have kind of a n00b problem, I can't seem to make HTTP GET requests from my Qt Code...

这是应该可以工作的代码:

Here is the code supposed to work:

void MainWindow::requestShowPage(){
    QNetworkAccessManager *manager = new QNetworkAccessManager(this);
    connect(manager,SIGNAL(finished(QNetworkReply*)),this,SLOT(requestReceived(QNetworkReply*)));
manager->get(QNetworkRequest(QUrl("http://google.com")));
}

void MainWindow::requestReceived(QNetworkReply* reply){
    QString replyText;
    replyText.fromAscii(reply->readAll());

    ui->txt_debug->appendPlainText(replyText);
}

但问题是这不起作用:在requestReceived(QNetworkReply* reply)中,replyText似乎是空的,reply->error() 返回 0 并且 reply->errorString() 返回未知错误".我现在真的不知道该怎么办...

But the problem is that this just doesn't work: In requestReceived(QNetworkReply* reply), replyText seems empty, reply->error() returns 0 and reply->errorString() returns "Unknown Error". I don't really know what to do right now...

有什么想法吗?

推荐答案

明显是重定向,不认为是错误.
您应该使用回复属性中提供的重定向 url 运行新请求,直到获得真实页面:

There is obviously a redirection, which is not considered as an error.
You should run a new request with the redirection url provided in the reply attributes until you get the real page:

void MainWindow::requestReceived(QNetworkReply *reply)
{
    reply->deleteLater();

    if(reply->error() == QNetworkReply::NoError) {
        // Get the http status code
        int v = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
        if (v >= 200 && v < 300) // Success
        {
             // Here we got the final reply
            QString replyText = reply->readAll();
            ui->txt_debug->appendPlainText(replyText);
        }
        else if (v >= 300 && v < 400) // Redirection
        {
            // Get the redirection url
            QUrl newUrl = reply->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl();
            // Because the redirection url can be relative,
            // we have to use the previous one to resolve it
            newUrl = reply->url().resolved(newUrl);

            QNetworkAccessManager *manager = reply->manager();
            QNetworkRequest redirection(newUrl);
            QNetworkReply *newReply = manager->get(redirection);

            return; // to keep the manager for the next request
        }
    }
    else
    {
        // Error
        ui->txt_debug->appendPlainText(reply->errorString());
    }

    reply->manager()->deleteLater();
}

您还应该记录重定向的位置或计算重定向的次数,以避免永无止境的循环.

You should also record where you are redirected or count the number of redirections, to avoid never ending loops.

这篇关于在 Qt 下制作 HTTP GET的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 17:57