Make HTTP POST request with a list of named parameters in Qt

Deadly 提交于 2020-01-11 12:08:15

问题


I need to make an HTTP POST request to a server from my Qt application.

The POST request would contain a list of named values, i.e. key/value pairs. They will be mostly alphanumeric strings, but can contain special characters such as quotes, spaces, etc.

What is the canonical way of doing this type of POST request in Qt?


回答1:


QUrl params;

params.addQueryItem("key1", "value1");
params.addQueryItem("key2", "value2");

QUrl resource("http://server.com/form.php");
QNetworkAccessManager* manager = new QNetworkAccessManager(this);

connect(manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(handleEndOfRequest(QNetworkReply*)));

QNetworkRequest request(resource);
//Force Content-Type header
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");

manager->post(request, params.encodedQuery());

This code assumes that your current object is a QObject (passed as a parent for QNeworkAccessManager and slots declaration)




回答2:


The current answer works for Qt 4. Syntax has changed for Qt 5 and would look like this:

QUrlQuery params;

params.addQueryItem("key1", "value1");
params.addQueryItem("key2", "value2");

QUrl resource("http://server.com/form.php");
QNetworkAccessManager* manager = new QNetworkAccessManager(this);

connect(manager, SIGNAL(finished(QNetworkReply*)), this, 
SLOT(handleEndOfRequest(QNetworkReply*)));

QNetworkRequest request(resource);
//Force Content-Type header
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");

manager->post(request, params.query(QUrl::FullyEncoded).toUtf8());

Some background information: http://doc.qt.io/qt-5/qurl-obsolete.html

Making Qt-version-aware code is described here: How do you port QUrl addQueryItem to Qt5's QUrlQuery?




回答3:


You can use QNetworkAccessManager together with QNetworkRequest to post http requests.
If you want to send key/value pairs, consider using JSON.



来源:https://stackoverflow.com/questions/18439138/make-http-post-request-with-a-list-of-named-parameters-in-qt

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!