PDA

View Full Version : Problem handling cookies with raw HTTP post request



ntXn
18th March 2013, 23:04
Hello, I'm new to Qt and I hope that someone can help me.

What I want to do is to get some data from index.php as a logged user and parse it later in my app. So I created a post request on index.php with regular post data for a form (username, password, action - all this stuff was sniffed when I was logging in with browser - so its exactly what the php expects), but I fail to handle cookies. Let me show the code:



QNetworkAccessManager *manager = new QNetworkAccessManager(this);

connect(manager,SIGNAL(finished(QNetworkReply*)),t his,SLOT(replyFinished(QNetworkReply*)));

QNetworkRequest request;
request.setUrl(QUrl("https://serveradress/index.php"));

QByteArray postData;
postData.append("Cookie: PHPSESSID=randomnumber;\n\n"); // sniffer I use says that no cookies were sent, but if I leave this out server says that I should enable cookies
postData.append("username=mylogin&password=mypassword&action=login"); // post data


manager->post(QNetworkRequest(request),postData);

But it still won't log me in (it says that username is empty - I noticed that after I log in with browser, server sends back more cookies containing also one username).
So I would like to handle cookies otherwise, from what I understand I need to get a fresh cookie from server and use that for further requests - or can I handle this in one single request, ignoring the cookies that server sends back to me ?

wysota
18th March 2013, 23:14
Cookies are not part of the message body but rather part of headers. Use QNetworkRequest::setHeader() or QNetworkRequest::setRawHeader() to set those.

ChrisW67
18th March 2013, 23:36
If you do a get plain GET on the login page to obtain session cookies (usually all that is required) you can let QNetworkAccessManager worry about sending the cookies with every subsequent request (including your POST). Set a custom QNetworkCookieJar on the QNetworkAccessManager if you need finer control.

DomantasB
30th October 2013, 13:45
I have exactly same problem. Could you please respond how you solved this or someone else please explain more in depth.

I tryed to use this line but it doesn't fix anything.


req.setRawHeader("Cookie: PHPSESSID", "19465198465198451681681");



and this is my thread please someone check it. (http://www.qtcentre.org/threads/56757-Problem-with-Qnetwork-cookies-and-getting-code-after-login)