Making an HTTP GET under Qt

前端 未结 2 1308
予麋鹿
予麋鹿 2020-12-10 07:13

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::request         


        
相关标签:
2条回答
  • 2020-12-10 07:42

    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.

    0 讨论(0)
  • 2020-12-10 08:03

    If reply->error() = 0, it means the request was successful. In fact, your code seems right to me, and the only thing I would do differently is to read the data. Try with this:

    QByteArray rawData = reply->readAll();
    QString textData(rawData);
    qDebug() << textData;
    
    0 讨论(0)
提交回复
热议问题