使用Qt进行HTTP GET请求

7

我有一个新手问题,我似乎无法从我的Qt代码中进行HTTP GET请求...

以下是应该正常工作的代码:

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()返回0reply->errorString()返回"未知错误"。我现在真的不知道该怎么办了...
有什么想法吗?
2个回答

11

显然存在一个重定向,这不被视为错误。
你应该使用响应属性中提供的重定向URL运行一个新请求,直到获取真实页面:

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();
}

你还应该记录重定向的位置或计算重定向的次数,以避免无限循环。


1
非常感谢!您的解决方案非常有效!我从来没有想到过... - m6a-uds
@alexisdm 你好,我遇到了类似的问题,但是我的重定向URL还包含了POST数据,是否有类似这段代码的解决方法? - thnkwthprtls

0
如果reply->error() = 0,那么这意味着请求成功。实际上,您的代码看起来没问题,唯一不同的是读取数据。尝试使用以下代码:
QByteArray rawData = reply->readAll();
QString textData(rawData);
qDebug() << textData;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接