Search code examples
qtqnetworkaccessmanagerqtnetworkqnetworkrequestqnetworkreply

QNetworkReply error "Connection closed" when getting a simple URL


I'm trying to make a simple file downloader. Here is my code segment for downloading a URL; This code works fine, if I try to get simple URLs like "http://stackoverflow.com".
But when I specify URLs which redirects, it throws an error saying "Connection closed".

//Sets a sample URL which redirects.
QString url = "http://downloads.sourceforge.net/project/gretl/gretl/1.9.92/gretl-1.9.92.tar.xz"

QNetworkAccessManager * networkAccessManager = new QNetworkAccessManager(this);

QNetworkRequest * networkRequest = new QNetworkRequest(QUrl(url));

//Getting the URL
QNetworkReply * networkReply = networkAccessManager->get(*networkRequest);

Additionally I've connected the following signal-slot to recognize network errors:

 //Connects networkReply object's error signal to a slot which prints the error.
 connect(networkReply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(printError(QNetworkReply::NetworkError)));

Here is the slot which prints errors if networkReply's error signal is emitted:

void printError(QNetworkReply::NetworkError code)
{
     qDebug() << "Network Error Code: " << code;
     qDebug() << networkReply->errorString();
}

Because of this error, networkReply object never receives any header.

My need is to read the HTTP status code by this method: QNetworkReply::attribute(QNetworkRequest::HttpStatusCodeAttribute)

I can't read the HTTP Status code, because I don't get the headers.

Can anyone say whats going on?
Thanks in advance! :)


Solution

  • Here and here are good examples of handling this scenario - basically you add a slot for finished signal, then check the HTTP status code for 301 and/or QNetworkRequest::RedirectionTargetAttribute attribute to see if you are being redirected and if so issue a new request for the redirect link.