第5课:Qt5 HTTP接口请求

现在的程序开发,都是前后端分离的。
比如一个登录功能,用户发出登录请求给服务端,服务端接受请求处理这两部分是分开的
服务端一般是提供通用的各终端接口
如果用Qt来请求http接口,该如何做呢?
一般情况下,接口返回值都是json,这里也以返回值为json为例
1.include必要的文件
#include <QtNetwork/QtNetwork>
#include <QJsonDocument>
#include <QJsonParseError>
#include <QJsonObject>

2.调用
这里以post请求为例,get也是类似的
void LoginDlg::on_loginBtn_clicked()
{
    QNetworkAccessManager *network_manager = new QNetworkAccessManager();
    QNetworkRequest network_request;
    QByteArray post_data;

    //设置发送的数据
    post_data.append("user=www.godeye.org&");
    post_data.append("pwd=www.godeye.org&");

    //设置头信息
    network_request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
    network_request.setHeader(QNetworkRequest::ContentLengthHeader, post_data.length());

    //设置url
    network_request.setUrl(QUrl("http://localhost/test.php"));

    //发送请求
    QNetworkReply *reply = network_manager->post(network_request, post_data);

    //connect(network_manager, &QNetworkAccessManager::finished, this, &HttpManager::replyFinished);
    connect(network_manager, SIGNAL(finished(QNetworkReply*)),
            this, SLOT(replyFinished(QNetworkReply*)));
}

void LoginDlg::replyFinished(QNetworkReply *reply) {
    if(reply->error() == QNetworkReply::NoError) {
        QByteArray bytes = reply->readAll();//获取字节
        QJsonParseError jsonpe;//JSON
        QJsonDocument json = QJsonDocument::fromJson(bytes, &jsonpe);
        if (jsonpe.error == QJsonParseError::NoError) {
            if (json.isObject()) {
                QJsonObject obj = json.object();
                if (obj.contains("error")) {
                    qDebug() << "error:" << obj["error"];
                } else {
                    if (obj["code"].toInt() == 1) {
                        accept();
                    } else {
                        QMessageBox::warning(this, tr("Waring"),
                                              tr("user name or password error!"),
                                              QMessageBox::Yes);
                    }
                }
            }
        } else {
            qDebug() << "error:" << jsonpe.errorString();
        }

    }
    else
    {
        //处理错误
        QMessageBox::warning(this, tr("Waring"),
                              tr("user name or password error!"),
                              QMessageBox::Yes);
    }
    reply->deleteLater();
}