Creating HTTP GET under Qt

I have n00b problem, I cannot force HTTP GET requests from my Qt code ...

Here is the code that should 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); } 

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

Any idea?

+6
source share
2 answers

Obviously there is a redirect that is not considered an error.
You should start a new request with the redirect URL specified in the response 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 redirects to avoid endless loops.

+9
source

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

 QByteArray rawData = reply->readAll(); QString textData(rawData); qDebug() << textData; 
0
source

Source: https://habr.com/ru/post/896061/


All Articles