QT实现GET或POST请求并返回JSON的方法,其中:1、如果是POST请求可以传递formdata参数;2:如果是GET请求可以传递URL参数(键值对),输入的URL允许带参数,参数拼接的问题,
时间: 2024-04-07 08:28:03 浏览: 114
Qt post请求发送和解析json数据完整示例,有完整的设置框架,可以发送和解析多个post请求
在QT中,可以使用QNetworkAccessManager类来发送网络请求并获取响应。具体实现方法如下:
1. 发送GET请求并获取JSON响应:
```cpp
QNetworkAccessManager *manager = new QNetworkAccessManager(this);
connect(manager, &QNetworkAccessManager::finished, this, [=](QNetworkReply *reply) {
if (reply->error() == QNetworkReply::NoError) {
QByteArray response = reply->readAll();
QJsonDocument jsonDoc = QJsonDocument::fromJson(response);
if (jsonDoc.isNull()) {
qWarning() << "Failed to parse JSON response.";
return;
}
QJsonObject jsonObj = jsonDoc.object();
// 处理JSON响应
} else {
qWarning() << "Failed to get response:" << reply->errorString();
}
});
QUrl url("http://example.com/api?param1=value1¶m2=value2");
QNetworkRequest request(url);
manager->get(request);
```
2. 发送POST请求并获取JSON响应:
```cpp
QNetworkAccessManager *manager = new QNetworkAccessManager(this);
connect(manager, &QNetworkAccessManager::finished, this, [=](QNetworkReply *reply) {
if (reply->error() == QNetworkReply::NoError) {
QByteArray response = reply->readAll();
QJsonDocument jsonDoc = QJsonDocument::fromJson(response);
if (jsonDoc.isNull()) {
qWarning() << "Failed to parse JSON response.";
return;
}
QJsonObject jsonObj = jsonDoc.object();
// 处理JSON响应
} else {
qWarning() << "Failed to get response:" << reply->errorString();
}
});
QUrl url("http://example.com/api");
QNetworkRequest request(url);
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
QUrlQuery query;
query.addQueryItem("param1", "value1");
query.addQueryItem("param2", "value2");
manager->post(request, query.toString(QUrl::FullyEncoded).toUtf8());
```
以上代码可以根据需要进行修改,比如更改URL、请求头、请求体等。
阅读全文