How to add request body when post a image in Qt? - qt

I am confusing when I want to post a image file to server. With a clear post, I can just use QHttpMultiPart ,and it works fine. But this time I want to add some params, the server just don't get them.
I have searched for days , But no solution is found.
The code goes like this:
QUrl url("http://192.168.1.211/v1");
QUrlQuery query;
//following params are what i want to add
query.addQueryItem("app_name", "pc");
query.addQueryItem("ip", "192.168.1.110");
query.addQueryItem("dev_os","android");
query.addQueryItem("dev_os_ver","11.4.1");
query.addQueryItem("dev_model",testEquip);
query.addQueryItem("latitude","23.137466");
query.addQueryItem("longitude","113.352425");
query.addQueryItem("user_id","1");
query.addQueryItem("nickname","nick");
query.addQueryItem("sex","1");
query.addQueryItem("headimgurl","http://some.com/");
url.setQuery(query);
QNetworkRequest req;
req.setUrl(url);
req.setRawHeader("X-Api-Key","JDZBNH3HDFI823AISDU9SF32IRJ");
QHttpMultiPart *multiPart=new QHttpMultiPart(QHttpMultiPart::FormDataType);
QHttpPart imagePart;
imagePart.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("image/jpeg"));
imagePart.setHeader(QNetworkRequest::ContentDispositionHeader,QVariant("form-data; name=\"image\"; filename=\""+filename+"\""));
QFile *file=new QFile(path);
file->open(QIODevice::ReadOnly);
imagePart.setBodyDevice(file);
file->setParent(multiPart);
multiPart->append(imagePart);
QNetworkAccessManager *manager=new QNetworkAccessManager();
QNetworkReply *reply=manager->post(req,multiPart);
multiPart->setParent(reply);
The response code shows no params have been accessed. So what is the right way to add these params?

Related

Logging into a remote website with QT5

I am attempting to create an application that can login to a website. The specific website is:
http://adfast.biz
Here is the code I am currently using:
void MainWindow::http_finish(QNetworkReply *reply)
{
int code = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
if (code >= 300 && code < 400)
{ //HTTP 3XX codes are redirections
QUrl redirectTo = reply->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl();
reply->manager()->get(QNetworkRequest(redirectTo));
return;
}
if (reply->error() == QNetworkReply::NoError)
{
QString Msg = QString::fromUtf8(reply->readAll());
if (cdone == 0)
{//Runs only once, causing a reload of the main page
++cdone;
QUrl URL("http://adfast.biz");
QNetworkRequest QNR(URL);
reply->manager()->get(QNR);
QMessageBox::information(0,"1)" + QString::number(code),Msg);
return;
}
QMessageBox::information(0,"2)" + QString::number(code),Msg);
}
else
{
QMessageBox::information(0,"Error:",reply->errorString());
}
reply->deleteLater();
}
void MainWindow::on_Send_clicked()
{
QNetworkAccessManager* MNAM = new QNetworkAccessManager(this); //Stored within QNetworkReply->manager()
connect(MNAM,SIGNAL(finished(QNetworkReply*)),this,SLOT(http_finish(QNetworkReply*)));
QUrlQuery postData;
postData.addQueryItem("email","mail#mail.net");
postData.addQueryItem("senha","Password");
postData.addQueryItem("logar","ok");
QUrl URL(ui->TXT_Input->toPlainText());
URL.setQuery(postData);
QNetworkRequest QNR(URL);
QNR.setHeader(QNetworkRequest::ContentTypeHeader,"application/x-www-form-urlencoded");
MNAM->post(QNR,URL.toEncoded());
}
I am guessing that I either am sending the information the wrong way or that I need to possibly manage cookies? Both responses come back with HTTP status code: 200. The first comes with no source the second comes with the full web-source but is NOT logged in. I am positive that the user-data being sent is correct, but not that it is being sent correctly.
Edit:
I've changed a little, with no luck. First I have added a cookie-jar using:
QNetworkAccessManager* MNAM = new QNetworkAccessManager(this); //Stored within QNetworkReply->manager()
QNetworkCookieJar* cJar = new QNetworkCookieJar;
MNAM->setCookieJar(cJar);
connect(MNAM,SIGNAL(finished(QNetworkReply*)),this,SLOT(http_finish(QNetworkReply*)));
Then, I tested to see if any cookies are being received using the following code at the top of MainWindow::http_finish:
QList<QNetworkCookie> cookies = reply->manager()->cookieJar()->cookiesForUrl(QUrl("http://adfast.biz/"));
QMessageBox::information(0,"Cookies",QString::number(cookies.count()));
I want to add that the post is being sent to: http://adfast.biz/login (That is the value of: ui->TXT_Input->toPlainText()) But it seems that I can't get this to login at all. And I am not sure what I'm missing.
So, I did manage to login into this site with testguest#yahoo.com and mypassword12. But I can only offer very quick and dirty code, which explains how. The 'polishing' you must do yourself. :-)
QFile f("/tmp/cookie.txt");
f.open(QIODevice::ReadOnly);
QDataStream s(&f);
while(!s.atEnd()){
QByteArray c;
s >> c;
QList<QNetworkCookie> list = QNetworkCookie::parseCookies(c);
qDebug() << "eee" << list;
jar->insertCookie(list.at(0));
}
connect(MNAM,SIGNAL(finished(QNetworkReply*)),
this,SLOT(http_finish(QNetworkReply*)));
QUrlQuery postData;
postData.addQueryItem("email","testguest#yahoo.com");
postData.addQueryItem("senha","mypassword12");
postData.addQueryItem("logar","ok");
//QUrl URL("http://adfast.biz/");
//QUrl URL("http://adfast.biz/anuncios_telexfree");
URL.setQuery(postData);
QNetworkRequest QNR(URL);
QNR.setHeader(QNetworkRequest::ContentTypeHeader,
"application/x-www-form-urlencoded");
MNAM->get(QNR);
Above code reads the cookies, which are written in the http_finish slot below into /tmp/cookie.txt.
The first time you run this code, you must uncomment the first URL, the second time, when you have your cookies, the second URL. Ignore that I made your post into a get. I did it just for debugging reasons.
void MainWindow::http_finish(QNetworkReply *reply){
qDebug() << reply->readAll();
QList<QNetworkCookie> list =
MNAM->cookieJar()->cookiesForUrl(QUrl("http://adfast.biz/"));
QFile f("/tmp/cookie.txt");
f.open(QIODevice::ReadWrite);
for(int i = 0; i < list.size(); ++i){
QDataStream s(&f);
s << list.at(i).toRawForm();
}
f.close();
}
The code above writes the cookies from http://adfast.biz/ into /tmp/cookie.txt. Below an example of a cookie, which I received:
2-Sep-2013 16:41:39 GMT; domain=adfast.biz; path=/3 16:41:39 GMT;
domain=adfast.biz; path=/n=adfast.biz; path=/
Summary: You must connect to http://adfast.biz/ to get your cookie. When you have it, you must again connect, but this time to http://adfast.biz/anuncios_telexfree.
You may need to add a QNetworkCookieJar to your QNetworkAccessManager for keeping and sending cookies between requests and responses. You can set your cookie jar by using QNetworkAccessManager::setCookieJar(QNetworkCookieJar* cookieJar). Have a look at the requests being sent using HttpFox in Firefox and you can see if there are any cookies being sent back and forth.
Try to connect:
connect(&MNAM,SIGNAL(authenticationRequired(QNetworkReply*,QAuthenticator*)),
this,SLOT(provideAuthentication(QNetworkReply*,QAuthenticator*)));
And create a slot:
void TrackerClient::provideAuthentication(QNetworkReply *reply,
QAuthenticator *auth){
Q_UNUSED(reply);
auth->setUser(<your username>);
auth->setPassword(<your password>);
}
Ok, second try. The idea to add a cookiejar is correct, but just adding the jar is not enough. I tried the following with another site, which requires login. I did work. For your site I don't have login and password, and since it is not English, it is a little bit too hard for me for a quick help. :-)
How the login procedure works on "my" site.
You go to the main url, e.g. www.mysite.something.
The site asks you for a cookie. You have none.
Your are redirected (status 302 temporary moved) to a
page www.mysite.something/takelogin.php <--- example.
You enter your credentials. You already do this in your postdata.addQuery calls.
You send your post. If your creds are ok, the site sends you a cookie.
So far so good. What did you wrong? Now that you have the cookie you must again go to www.mysite.something. You are not automatically logged in and redirected to the main page of your site. And keep in mind, that cookies in QNetworkCookieJar are not stored on disk. They are only kept in memory. So, if your jar/MNAM is deleted, everything is gone.
You can easily store your received cookies to disk using the toRawForm() method of QNetworkCookie. To restore the cookie use the static QNetworkCooky::parseCookies(const QByteArray &cookieString) method.
Oh, almost forgot: The main url www.mysite.something did not send any cookies. I had to follow the redirect www.mysite.something/takelogin.php.
Disclaimer: It worked on my site. I don't know, if this is general for all sites, which require a login.
Checked with wrong creds: I was redirected to adfast.biz/login. This seems to be your redirect login page. More I cannot do without real creds.

How to use post() in qt?

This is my program. In this program I want to send request to a website (for example: http://www.adobe.com/products/muse.html)
I want to show the html code that return me in plain text box.
QUrl url("http://www.adobe.com/products/muse.html")
I want to give html code in "thisfile"
file.setFileName("thisfile.html");
if (!file.open(QIODevice::WriteOnly))
{
std::cerr << "Error: Cannot write file "
<< qPrintable(file.fileName()) << ": "
<< qPrintable(file.errorString()) << std::endl
return false;
}
http.setHost(url.host(),80);
http.post(url.toString(),"term=yyyy&loc=en_us&siteSection=products%3Amuse",&file);
This code doesn't work correctly and when I show the file give me false html code. What do I have to do?
Use http.get() instead of http.post() as POST method requires to set other Headers used by server.
QHttp::get() method is asynchronous too.
As your case is simple enough just to retrieve HTML response, you should go for HTTP GET IMHO. See difference between GET and POST method.
And if you have to use HTTP POST only, then check this.
QNetworkRequest request;
request.setUrl(QUrl("thisfile.html"));
QNetworkReply *reply = manager->post(request, "term=yyyy&loc=en_us&siteSection=products%3Amuse");
connect(reply, SIGNAL(readyRead()), this, SLOT(slotReadyRead()));
Look at QNetworkAccessManager at qt docs
You have to read information and save it to file at readyRead function

How to send data back from PHP after a HTTP Post in Qt?

I'm using this code to make a simple HTTP Post ( a login )
QNetworkAccessManager *nwam = new QNetworkAccessManager;
QNetworkRequest request(QUrl("http://localhost/laptop/trylogin.php"));
QByteArray data;
QUrl params;
QString userString(user);
QString passString(pass);
params.addQueryItem("user", userString );
params.addQueryItem("pass", passString );
data.append(params.toString());
data.remove(0,1);
QNetworkReply *reply = nwam->post(request,data);
If the logging succeedes or not, how do i send and read the response in Qt ?
You get the response / reply in the reply pointer.
Use QNetworkReply::error() to see if there was an error.
You can catch reply signals cause it works with Signals and slots.. So you have to connect a slot to the signal httpreadyread emitted by reply and then read the reply by reply.readAll method.. READ qtnetwork module documentation..

Whats the problem with my code (http post)

i am developing a simple application which uploads image to yfrog.com.(These images will be reflected in twitter account). Here is my code. but it is not working. I am not getting response from server.
QNetworkAccessManager *manager = new QNetworkAccessManager(this);
QNetworkRequest request(QUrl("http://yfrog.com/api/uploadAndPost"));
QByteArray data;
QUrl params,params1;
QFile file("some image path");
QString boundary("-----abcde12345");
QString body = "\r\n--" + boundary + "\r\n";
params.addQueryItem("username",twitterusername);
params.addQueryItem("password",twitterpassword);
params.addQueryItem("message",some message...);
params.addQueryItem("key",mydeveloperkey);
data.append(body);
data.append(params.toString());
QByteArray ba;
ba=file.readAll();
QString body1(ba);
params1.addQueryItem("media",body1);
data.append(params1.toString());
data.append(body);
request.setRawHeader("Content-Type","multipart/form-data; boundary=-----abcde12345");
request.setHeader(QNetworkRequest::ContentLengthHe ader,data.size());
QNetworkReply *reply = manager->post(request,data);
reply->waitForReadyRead(-1);
qDebug() << "replay :"<<reply->readAll();
If i checked the requested TCP packets from wireshark, it is giving a error message like 'malformed packets'.
For reference : http://code.google.com/p/imageshacka...GuploadAndPost
Please any body help regarding this. Where i am doing wrong?
QNetworkReply::waitForReadyRead does not have an implementation so it always refers the base class waitForReadyRead() (in this case QIODevice). In the base class, you will see that waitForReadyRead always returns FALSE.
From the docs, you would have to instead use the readRead() signal in QNetworkReply and read the data when the slot is called.
QNetworkReply *reply = manager->get(request);
connect(reply, SIGNAL(readyRead()), this, SLOT(slotReadyRead()));

QHttpMultiPart POST returns error 500

I'm experimenting with multi-part form submissions for the purpose of uploading files to a web server. I adapted the following code from the sample found in the documentation for QHttpMultiPart:
QHttpMultiPart * pMultiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType);
QHttpPart textPart1;
textPart1.setHeader(QNetworkRequest::ContentDispositionHeader, "form-data; name=\"Sport1\"");
textPart1.setBody("Dodgeball");
pMultiPart->append(textPart1);
QHttpPart textPart2;
textPart2.setHeader(QNetworkRequest::ContentDispositionHeader, "form-data; name=\"Sport2\"");
textPart2.setBody("Kickball");
pMultiPart->append(textPart2);
QNetworkRequest request(myUrl);
QNetworkReply * pReply = m_pNetworkManager->post(request, pMultiPart);
pMultiPart->setParent(pReply);
connect(pReply, SIGNAL(finished()), this, SLOT(replyFinished()));
The server keeps rejecting the submission with error 500. The problem is definitely not the script that is receiving the data as I have reduced it to simply return "Hello World" no matter what the request.
It seems that Qt (version 5.5) is doing something wrong with the boundary. I was able to get it to work by both setting the boundary to a string of my own choosing and by setting the header which specifies the boundary.
I added these two lines:
pMultiPart->setBoundary("---------------------jasglfuyqwreltjaslgjlkdaghflsdgh");
...
request.setHeader(QNetworkRequest::ContentTypeHeader, "multipart/form-data; boundary=" + pMultiPart->boundary());
Here it is all together:
QHttpMultiPart * pMultiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType);
pMultiPart->setBoundary("---------------------jasglfuyqwreltjaslgjlkdaghflsdgh");
QHttpPart textPart1;
textPart1.setHeader(QNetworkRequest::ContentDispositionHeader, "form-data; name=\"Sport1\"");
textPart1.setBody("Dodgeball");
pMultiPart->append(textPart1);
QHttpPart textPart2;
textPart2.setHeader(QNetworkRequest::ContentDispositionHeader, "form-data; name=\"Sport2\"");
textPart2.setBody("Kickball");
pMultiPart->append(textPart2);
QNetworkRequest request(myUrl);
request.setHeader(QNetworkRequest::ContentTypeHeader, "multipart/form-data; boundary=" + pMultiPart->boundary());
QNetworkReply * pReply = m_pNetworkManager->post(request, pMultiPart);
pMultiPart->setParent(pReply);
connect(pReply, SIGNAL(finished()), this, SLOT(replyFinished()));

Resources