PDA

View Full Version : Send JSON & Key via HTTP POST



Poonarge
20th August 2014, 12:28
Having trouble sending JSON & Key via POST




QByteArray jsonString = "{}";

QByteArray postDataSize = QByteArray::number(jsonString.size());

QUrl req("webpagehere");
req.setQuery("Key=XXXXXXXXXXXXX");

QNetworkRequest request(req);

request.setRawHeader("User-Agent", "Test");
request.setRawHeader("X-Custom-User-Agent", "Test");
request.setRawHeader("Content-Type", "application/json");
request.setRawHeader("Content-Length", postDataSize);

QNetworkAccessManager test;

QEventLoop loop;
connect(&test, SIGNAL(finished(QNetworkReply*)), &loop, SLOT(quit()));
QNetworkReply * reply = test.post(request, jsonString);
connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(onError(QNetworkReply::NetworkError)));
loop.exec();

QByteArray response = reply->readAll();
qDebug() << response;



Is there anything wrong with this code? or is it my webpage which is at fault? or possibly both?

Regards,

Richard

wysota
20th August 2014, 13:27
I would guess that your request's body is not properly formatted and the webserver rejects the request.

ChrisW67
20th August 2014, 21:18
You do not need to set the Content-Length header yourself, Qt will do that when you call post().

Are you sure that the server is expecting the key in the query string and raw JSON data in the post body and not:

A URL encoded body with multiple parameters encoded (application/x-www-form-urlencoded), or
A multipart/form-data payload?


Are you sure the server is expecting application/json as the content type and not one of the other, non-standard types used for JSON?
Is the JSON string UTF8 encoded?

Without seeing any error information or server logs we can only guess.

Poonarge
21st August 2014, 09:13
Thanks for the replies. The server was expecting form data.

Have now fixed this to send multipart/form-data and it's working a dream!

Many Thanks,

Richard