http post data encoding
-
wrote on 11 Apr 2016, 06:15 last edited by
I am trying to create a post request
QNetworkAccessManager *manager = new QNetworkAccessManager(this); request.setUrl(QUrl(settings.value("app/domainName").toString())); request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded"); QByteArray postData = "json_data="+json.toJson(); QObject::connect(manager, SIGNAL(finished(QNetworkReply *)), this, SLOT(updateToServerReplyFinished(QNetworkReply *))); manager->post(request, postData);
this works fine but the special character in post data cause error, How can I escape these characters from the post data ?
-
wrote on 11 Apr 2016, 06:27 last edited by
Hi @4j1th,
First off, do you actually need to be using WWW form encoding? If you control the server, then you might want to skip that encoding, in which case, you'd so something like:
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json"); QByteArray postData = json.toJson();
But if you do need to use form encoding, you'll want to do something like:
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded"); QByteArray postData = "json_data="+QUrl::toPercentEncoding(json.toJson());
Cheers.
-
Hi @4j1th,
First off, do you actually need to be using WWW form encoding? If you control the server, then you might want to skip that encoding, in which case, you'd so something like:
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json"); QByteArray postData = json.toJson();
But if you do need to use form encoding, you'll want to do something like:
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded"); QByteArray postData = "json_data="+QUrl::toPercentEncoding(json.toJson());
Cheers.
wrote on 11 Apr 2016, 06:43 last edited byHi @Paul-Colby , by using the first method how can I access the file (in server), is it works as a file uploading method ?
-
wrote on 11 Apr 2016, 07:08 last edited by
@4j1th said:
Hi @Paul-Colby , by using the first method how can I access the file (in server), is it works as a file uploading method ?
It depends on your server. What language is your server written with? (Assuming you're POSTing to your own server, and not some third-party API).
For example, the server was running PHP, you could do something like:
$data = json_decode(file_get_contents('php://input'), true); // save $data to a file somewhere.
In that case, you wouldn't need to use WWW form encoding.
2/4