PDA

View Full Version : How to download a file using HTTP with URL in QT?



Gokulnathvc
8th March 2011, 05:10
QUrl url = QUrl::fromUserInput(strUrl);
QFileInfo fileInfo(url.path());
QString fileName=fileInfo.fileName();
if (QFile::exists(fileName)) {
QMessageBox::information(this, tr("HTTP"),
tr("There already exists a file called %1 in "
"the current directory.")
.arg(fileName));
}

file = new QFile(fileName);
if (!file->open(QIODevice::WriteOnly)) {
QMessageBox::information(this, tr("HTTP"),
tr("Unable to save the file %1: %2.")
.arg(fileName).arg(file->errorString()));
delete file;
file = 0;
}

file.setFileName(fileName);
file.open(QIODevice::WriteOnly);
QHttp *http;
http=new QHttp(this);
setHost(url.host(),QHttp::ConnectionModeHttp);


Am getting while using the HTTP . It says undefined reference to the http object.
I just want to download a file from the host.

squidge
8th March 2011, 07:51
What include files have you specified?

Gokulnathvc
8th March 2011, 09:45
I have included <QNetworkAccessManager>, <QHttp>

stampede
8th March 2011, 10:06
And you have no other errors during compilation ? Do you have Qt += network in .pro file ?

Gokulnathvc
8th March 2011, 10:14
No. I dont have errors. And also no Qt +=network in my .pro file.

stampede
8th March 2011, 10:18
And also no Qt +=network in my .pro file
So add it;)

Archa4
8th March 2011, 10:18
Well if u want to work with network u have to have the Qt += network

Gokulnathvc
8th March 2011, 11:49
Yes, I have added it. Upto this everything is fine. Next is how to download that file.

Added after 1 4 minutes:

Here is the code:: Pls help me..


QUrl url = QUrl::fromUserInput(strUrl);

QFileInfo fileInfo(url.path());

QString fileName=fileInfo.fileName();

if (QFile::exists(fileName)) {

QMessageBox::information(this, tr("HTTP"),

tr("There already exists a file called %1 in "

"the current directory.")
.arg(fileName));

}



file = new QFile(fileName);

if (!file->open(QIODevice::WriteOnly)) {

QMessageBox::information(this, tr("HTTP"),

tr("Unable to save the file %1: %2.")

.arg(fileName).arg(file->errorString()));

delete file;

file = 0;
}



file.setFileName(fileName);
file.open(QIODevice::WriteOnly);

QHttp http;
QEventLoop loop;
QFile file;
QObject::connect(&http, SIGNAL(done(bool)), &loop, SLOT(quit()));

file.setFileName(filename);
file.open(QIODevice::WriteOnly);

http.setHost(url.host(), url.port(80));
http.get(url.toEncoded(QUrl::RemoveScheme | QUrl::RemoveAuthority),
&file);

loop.exec();

Berryblue031
8th March 2011, 12:27
You should consider using QAccessManager instead since QHttp is obsolete and qt strongly recommends not using it in new code



QNetworkAccessManager* mNetworkManager = new QNetworkAccessManager(this);
QObject::connect(mNetworkManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(onNetworkReply(QNetworkReply*)));

QUrl url = "http://someurl.com";
QNetworkReply* reply = mNetworkManager->get(QNetworkRequest(url));

void onNetworkReply(QNetworkReply* reply)
{
QString replyString;
if(reply->error() == QNetworkReply::NoError)
{
int httpstatuscode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute ).toUInt();
switch(httpstatuscode)
{
case RESPONSE_OK:
if (reply->isReadable())
{
//Assuming this is a human readable file replyString now contains the file
replyString = QString::fromUtf8(reply->readAll().data());
}
break;
case RESPONSE_ERROR:
case RESPONSE_BAD_REQUEST:
default:
break;
}
}

reply->deleteLater();
}

Gokulnathvc
8th March 2011, 12:46
It says incomplete type struct QNetworkRequest and lot more errors.. Could you pls help me..

Berryblue031
8th March 2011, 12:53
You need include


#include <QtNetwork/QNetworkReply>
#include <QtNetwork/QNetworkAccessManager>

in your cpp file

Gokulnathvc
8th March 2011, 13:05
It shows RESPONSE_ERROR was not declared in this scope..

Berryblue031
9th March 2011, 11:32
RESPONSE_OK, RESPONSE_ERROR, and RESPONSE_BAD_REQUEST are integers you need to define yourself depending on what status codes your webserver returns,

http://en.wikipedia.org/wiki/List_of_HTTP_status_codes

Gokulnathvc
10th March 2011, 12:07
Could you please explain the complete downloading of the file from the Host to the local machine?? please help me:confused:

squidge
10th March 2011, 13:15
It's documented and even coded for you above by Berryblue031, which part don't you understand?

Gokulnathvc
10th March 2011, 13:36
No actually. its not getting saved in the QFile. How to save that and also QNetworkreply shows errors like.. invalid struct. declaration error.

squidge
10th March 2011, 18:14
You need to be more descriptive.

Berryblue031
11th March 2011, 12:40
If you take a look at the documentation qnetworkreply->readAll().data() returns a qbytearray and QFile.write takes a qbytearray, so simply create your file like you did in your orignal code and read in the data from the qnetworkreply.

If you check the documentation this example http://doc.trolltech.com/4.7-snapshot/network-http.html does everything you are trying to do.

Gokulnathvc
14th March 2011, 06:02
File is created but empty one.. How to read it properly from http and write it to a file.

Added after 1 7 minutes:

QHttp http;
QFile file;
file.setFileName("C:\\Qt\\OCZToolbox\\"+fileName+".vic");
//http.setSocket(&socket);
//header.setValue("HOST",strhost);
//QHttp::ConnectionMode mode = url.scheme().toLower() == "https" ? QHttp::ConnectionModeHttps : QHttp::ConnectionModeHttp;
//socket.connectToHost(url.host(),80);
//http.setHost(url.host());
//int httpGetId = http.get(url.path(), &file);

connect (&http, SIGNAL(done(bool)), this, SLOT(httpDone(bool)));
//QUrl &url;
http.setHost(url.host(),QHttp::ConnectionModeHttp) ;
http.get(url.path(),&file);

//http.request(header,0);

file.open(QIODevice::WriteOnly);
//file.write(http.readAll());
file.close();
http.close();

Using this code Qfile is created but it is 0 kb. nothing is inside.. pls pls pls help me

ChrisW67
14th March 2011, 06:37
I don't know why you are persisting with using QHttp when both the posts in this thread and the advice in the Qt documentation tell you to use QNetworkAccessManager. From the QHttp docs:

This class is obsolete. It is provided to keep old source code working. We strongly advise against using it in new code.

and
This class provides a direct interface to HTTP that allows you to download and upload data with the HTTP protocol. However, for new applications, it is recommended to use QNetworkAccessManager and QNetworkReply, as those classes possess a simpler, yet more powerful API and a more modern protocol implementation.
You do have a good reason... don't you? If you were using the recommended network classes then you would find there are examples doing exactly this sort of thing.

Here is your code without your hack and slash commenting,. and with some comments of my own.


QHttp http; // Deprecated class, please use QNetworkAccessManager

// Define a file
QFile file;
file.setFileName("C:\\Qt\\OCZToolbox\\"+fileName+" .vic");
// file is not open for read or write

connect (&http, SIGNAL(done(bool)), this, SLOT(httpDone(bool)));
http.setHost(url.host(),QHttp::ConnectionModeHttp) ;

// Try to get a the URL response into the file that is not open for writing
http.get(url.path(),&file);

// That was an asynchronous operation you just started, so we get here immediately

// Ignore the fact that you have asked QHttp to write the file and try to do it yourself
// Open for writing and truncate any existing file
file.open(QIODevice::WriteOnly);
// write nothing to the file and then close
file.close();

http.close();

I have no idea why you are surprised that the file is empty.

Gokulnathvc
14th March 2011, 06:46
Could to please help me this code to work on using QNetworkAccessManager??? Kindly help me...

Could you please help me in downloading this .... using QNetWorkAccessManager.. kindly help me

ChrisW67
14th March 2011, 07:14
It looks like you started by copy-n-paste from one of the examples but, when it didn't Just Work, you thrashed about looking for another cut-n-paste code snippet rather than trying to understand why it didn't work.

Stop hacking at your code. Open Qt Assistant, navigate to the "Qt Reference Documentation", then "Tutorials and Examples", then "Network" examples. There are three examples you should study (in order):

HTTP
Download
Download Manager
They all compile, work, and download file(s) with varying degrees of complexity. When you find something in the examples that you do not understand then ask.

Also, read back through this thread, especially the post by Berryblue031.

You wondered what RESPONSE_ERROR the other constants were: user-defined symbolic names for HTTP status codes (http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html)

Gokulnathvc
14th March 2011, 11:47
Yes, now the file is downloaded. But Am not getting the file with actual size..

squidge
14th March 2011, 13:25
Yes, now the file is downloaded. But Am not getting the file with actual size..Sorry, my crystal ball is broken. Care to give us a bit more information?

wysota
14th March 2011, 14:22
Sorry, my crystal ball is broken.
You should really get a spare one :P

squidge
14th March 2011, 16:10
Do you know how much crystal balls are now? I can't really afford a spare one.

ChrisW67
14th March 2011, 21:58
Crystal balls are issued free to Masters of Zen but mere Experts have to provide their own - get used to the idea ;)
My crystal ball predicts that this thread is not dead yet.

Gokulnathvc: Here is how to ask your question:

I have am trying to download a {binary/text} {PDF/database/Transylvanian folk remedy} file using HTTP, QNetworkAccessManager and code based on the XYZ example from Assistant. My actual code is:


// my actual code, inside [code ]...[/code ] tags, and distilled down to a small
// compilable example that demonstrates the problem

The request is being processed and there I am seeing a signal that the request is done. However, when I save the data my file is not empty but it is also not complete. As you can see every call that generates a true/false status or error code return value is being checked and there are no errors being reported. I have tried other files and {insert what happened differently}. I've also tried other web sites and {insert more evidence you have tried to solve this yourself}.

If I use the example code without modification then the file is downloaded OK. The differences between my code and the example are {insert description here} or:


// more code differences inside [code ]...[/code ] tags

I have tried {more stuff} with {more results} but I really cannot see what I am doing wrong.

Could someone please provide advice so that I can solve my problem?

Gokulnathvc
15th March 2011, 06:50
Thanks for you kind co-operation. I have fixed it. I have added finished() function under this. Now its working fine.. Thank you