How can I POST data to a url using QNetworkAccessManager
I used:
QByteArray postData;
postData.append("param1=string&");
postData.append("param2=string");
So & instead of newline after each parameter.
Updating alexisdm answer to Qt5:
// Setup the webservice url
QUrl serviceUrl = QUrl("http://your.url");
QByteArray postData;
QUrlQuery query;
query.addQueryItem("param1","string1");
query.addQueryItem("param2","string2");
postData = query.toString(QUrl::FullyEncoded).toUtf8();
// Call the webservice
QNetworkAccessManager *networkManager = new QNetworkAccessManager(this);
connect(networkManager, SIGNAL(finished(QNetworkReply*)),
SLOT(onPostAnswer(QNetworkReply*)));
QNetworkRequest networkRequest(serviceUrl);
networkRequest.setHeader(QNetworkRequest::ContentTypeHeader,"application/x-www-form-urlencoded");
networkManager->post(networkRequest,postData);
Don't forget to include
QT += network
in .pro.
Since some parameters and values might need to be utf-8 and percent encoded (spaces, &, =, special chars...), you should rather use QUrl
(for Qt 4) or QUrlQuery
(for Qt 5) to build the posted string.
Example code for Qt 4:
QUrl postData;
postData.addQueryItem("param1", "string");
postData.addQueryItem("param2", "string");
...
QNetworkRequest request(serviceUrl);
request.setHeader(QNetworkRequest::ContentTypeHeader,
"application/x-www-form-urlencoded");
networkManager->post(request, postData.encodedQuery());
and for Qt 5:
QUrlQuery postData;
postData.addQueryItem("param1", "string");
postData.addQueryItem("param2", "string");
...
QNetworkRequest request(serviceUrl);
request.setHeader(QNetworkRequest::ContentTypeHeader,
"application/x-www-form-urlencoded");
networkManager->post(request, postData.toString(QUrl::FullyEncoded).toUtf8());
Starting with Qt 4.8 you can also use QHttpMultiPart if you need to upload files.