qt http post
时间: 2023-08-31 18:12:32 浏览: 36
To make an HTTP POST request in Qt, you can use the QNetworkAccessManager class. Here's an example:
```
QNetworkAccessManager* manager = new QNetworkAccessManager(this);
QUrl url("http://example.com/api");
QNetworkRequest request(url);
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
QJsonObject json;
json["name"] = "John";
json["age"] = 30;
QByteArray postData = QJsonDocument(json).toJson();
QNetworkReply* reply = manager->post(request, postData);
connect(reply, &QNetworkReply::finished, [=]() {
if (reply->error() == QNetworkReply::NoError) {
// Success
QByteArray responseData = reply->readAll();
qDebug() << responseData;
} else {
// Error
qDebug() << "Error:" << reply->errorString();
}
reply->deleteLater();
});
```
This example sends a JSON object as the POST data to the specified URL. The `QNetworkRequest::ContentTypeHeader` is set to indicate that the data is in JSON format. The response is handled in the `finished` slot of the reply object. If there is no error, the response data is read and printed to the console. If there is an error, the error message is printed. Finally, the reply object is deleted to free up resources.