我正在尝试使用Qt框架从URL中提取JSON数据,并且我遇到了从get请求返回的一些问题。我已经看到有关我的问题的多个问题,但是没有一个给定的解决方案解决了我的问题。
所以我有一个按钮,一旦点击,就应该执行get请求。这是我的代码。
//When button is pressed
void Test1::onClickCapture()
{
qDebug() << "Capture Clicked!!";
toPopulate();
}
//Code to execute the connection
void Test1::toPopulate() {
qDebug() << "Populating!";
QNetworkAccessManager* manager = new QNetworkAccessManager(this);
QNetworkRequest request;
QUrl url("https://jsonplaceholder.typicode.com/posts/1");
request.setUrl(url);
QNetworkReply *reply = manager->get(request);
connect(reply, &QNetworkReply::readyRead, this, &Test1::onResult);
}
//And finally, my onResult slot
void Test1::onResult() {
reply->deleteLater();
if (reply->error() != QNetworkReply::NoError) {
return;
}
qDebug() << "Response!";
}
每次调试代码时,它都不会进入我的onResult插槽。
我也得到了这个错误,这可能是相关的。
QObject :: connect:无法连接(null):: aboutToQuit()到QNativeWifiEngine :: closeHandle()
答案 0 :(得分:0)
我修改了你的代码。它对我来说很好:
//Code to execute the connection
void MainWindow::toPopulate() {
qDebug() << "Populating!";
QNetworkAccessManager* manager = new QNetworkAccessManager(this);
QNetworkRequest request;
QUrl url("https://jsonplaceholder.typicode.com/posts/1");
request.setUrl(url);
QNetworkReply *reply = manager->get(request);
connect(reply, SIGNAL(downloadProgress(qint64,qint64)), this, SLOT(downloading(qint64,qint64)));
connect(reply, SIGNAL(finished()), this, SLOT(onResult()));
}
void MainWindow::downloading(qint64 bytesReceived, qint64 bytesTotal) {
qDebug() << "Downloading " << bytesReceived/bytesTotal*100 << " %.";
}
//And finally, my onResult slot
void MainWindow::onResult() {
QNetworkReply* reply = qobject_cast<QNetworkReply*> (QObject::sender());
if (reply->error() != QNetworkReply::NoError) {
qDebug() << "Error downloading. " << reply->errorString();
return;
}
reply->deleteLater();
qDebug() << "Response! " << reply->readAll();
}
结果:
Populating!
Downloading -29200 %.
Downloading 100 %.
Response! "{\n \"userId\": 1,\n \"id\": 1,\n \"title\": \"sunt aut facere repellat provident occaecati excepturi optio reprehenderit\",\n \"body\": \"quia et suscipit\\nsuscipit recusandae consequuntur expedita et cum\\nreprehenderit molestiae ut ut quas totam\\nnostrum rerum est autem sunt rem eveniet architecto\"\n}"