2016-07-26 8 views
0

Ich versuche, JSON-Daten aus einer URL mit dem Qt-Framework zu ziehen, und ich habe einige Probleme mit einer Rückgabe von der Get-Anfrage erhalten. Ich habe mehrere Fragen zu meinem Problem gestellt, aber keine der angegebenen Lösungen hat mein Problem gelöst.Qt Netzwerk Access Manager JSON Antwort erhalten

Also habe ich eine Schaltfläche, die, einmal geklickt, sollte die Anforderung ausführen. Hier ist mein Code.

//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!"; 
} 

Jedes Mal, wenn ich den Code debuggen, wird es nie zu meinem onResult-Steckplatz.

Ich bekomme auch diesen Fehler, der relevant sein kann.

QObject :: connect: Kann nicht (null) verbinden :: aboutToQuit(), um QNativeWifiEngine :: Closehandle()

Antwort

0

ich Ihren Code geändert haben. Es funktioniert gut für mich:

//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(); 
} 

Ergebnis:

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}"