1

I am doing a simple HTTP get request to www.google.co.in but I am getting empty string in response.

Here is my code:

void MainWindow::on_pushButton_clicked()
{
    QNetworkAccessManager * mgr = new QNetworkAccessManager(this);
    connect(mgr,SIGNAL(finished(QNetworkReply*)),this,SLOT(onfinish(QNetworkReply*)));

    QUrl url("www.google.co.in");
    url.setScheme("http");
    QNetworkRequest request(url);
    request.setHeader(QNetworkRequest::ContentTypeHeader,"application/json");
    mgr->get(QNetworkRequest(QUrl("www.google.co.in")));


}

void MainWindow::onfinish(QNetworkReply *rep)
{
    QByteArray bts = rep->readAll();
    QString str(bts);
    qDebug() << str;

}

Output is :""

Facing same issue when doing post request to my own server.

In pro file I have done QT += core gui network

1 Answer 1

3

You have to add the correct URL, in addition it is recommended that you use the new connection between signals and slots, and finally you must remove the QNetworkReply:

void MainWindow::on_pushButton_clicked()
{
    QUrl url("https://www.google.co.in/");
    QNetworkAccessManager *mgr = new QNetworkAccessManager(this);
    connect(mgr,&QNetworkAccessManager::finished,this,&MainWindow::onfinish);
    mgr->get(QNetworkRequest(url));

}

void MainWindow::onfinish(QNetworkReply *rep)
{
    QByteArray bts = rep->readAll();
    QString str(bts);
    qDebug() << str;
    rep->deleteLater();
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.