本文介绍了在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...

这是应该工作的代码:

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 *回复) replyText 似乎为空,回复 - >错误()返回 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...

任何想法?

推荐答案

显然有重定向,不会被视为错误。

您应该使用回复属性中提供的重定向网址运行新请求,直到获得真实页面为止:

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