Qt5 posting data to server using QUrl / QNetworkRequest
Asked Answered
S

3

8

I have a piece of code that worked in 4.8 but now I need to port it to Qt5 (beta2)
This is what should happen:
I want to post some data to a webserver the url should look like this "http://server/actions.php" Then my fields (a "Action" -string and a "data" string(json)) should be sent to the server using post. Not encoded in the url

QUrl params;
// The data to post
QVariantMap map;

map["Title"]="The title";
map["ProjectId"]="0";
map["Parent"]="0";
map["Location"]="North pole";
map["Creator"]="You";
map["Group"]="a group";
QByteArray data = Json::serialize(map); //the map is converted to json im a QByteArray

params.addEncodedQueryItem("Data",data);
params.addQueryItem("Action", "Update");

QNetworkRequest Request(QUrl("http://server.com/actions.php"));
Request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
NetManager->post(Request,params.encodedQuery());

Now, I might not be doing this right in the first place,(It worked in 4.8) but the real problem is that addEncodedQueryItem() and addQueryItem() are now gone since Qt5 and I don't know what I should replace them with.
I have read the new docs and see the new QUrlQuery but I could not figure out on my own how to use this in my case.

Simulant answered 26/11, 2012 at 12:25 Comment(0)
F
6

I faced similar problem and used code similiar to the following in Qt5

QUrl url;
QByteArray postData;

url.setUrl("http://myurl....");
QNetworkRequest request(url);
request.setHeader(QNetworkRequest::ContentTypeHeader,"application/x-www-form-urlencoded");

Qstring postKey = 'city';
QString postValue = 'Brisbane';

postData.append(postKey).append("=").append(postValue).append("&");         
networkManager.post(request,postData);

Hope it might be useful to rewrite your code to send http post values using Qt5

Futures answered 11/1, 2013 at 6:43 Comment(0)
C
1

Qt5 no longer has the QUrl::encodedQuery() method. Not sure, but from the documentation it might work using QUrl::query() method instead.

Hope it helps.

Comitative answered 27/11, 2012 at 15:18 Comment(0)
I
0

QUrlQuery() helps you encode POST data.
Example in PyQt 5.4:

params = QtCore.QUrlQuery()
params.addQueryItem("username", "Вагиф Plaît")
reply = QtNetwork.QNetworkAccessManager().post(request, params.toString(QtCore.QUrl().FullyEncoded))
Imitate answered 15/1, 2017 at 6:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.