闲情zhi

生活 创业 时评 杂文

Qt应用开发学习(5) – Qt发送Http请求(Post/get)

qt的http请求还是很简单的

比如get请求

QEventLoop eventLoop;

    //request login api
    QNetworkAccessManager netManage;
    QNetworkRequest netReq(QUrl(QString("https://www.baidu.co/auth/login")));

//    netReq.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
    QObject::connect(&netManage, SIGNAL(finished(QNetworkReply*)), &eventLoop, SLOT(quit()));

    QNetworkReply *netReply = netManage.get(netReq);
    eventLoop.exec();

    qDebug() <<  "success" << netReply->readAll();

这边也红了eventLoop这个,自己写的话去掉问题也不大。

post请求则需要更多的信息

QNetworkAccessManager netManage;
    QNetworkRequest netReq(QUrl(QString("https://www.baidu.co/auth/login")));

    netReq.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");

    //data params
    QUrlQuery postData;
    QByteArray params;

    postData.addQueryItem("email", "contact@222.co");
    postData.addQueryItem("passwd", "2222");

    params.append(postData.toString());

    QObject::connect(&netManage, SIGNAL(finished(QNetworkReply*)), &eventLoop, SLOT(quit()));

    QNetworkReply *netReply = netManage.post(netReq, params);
    eventLoop.exec();

    ui->pushButton->setText("Login Completed");

    qDebug() <<  "success" << netReply->readAll();


Leave a Reply

Your email address will not be published.