QT http请求数据

1.创建一个请求类(HttpWork)

HttpWork.h头文件

#pragma once

#include <QObject>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include "NetWorkCookie.h"
#include <QNetworkCookie>

class HttpWork : public QObject
{
    Q_OBJECT

public:
    HttpWork(QObject *parent,bool ssl=false,bool autoDelete = true);
    ~HttpWork();
    void get(QString url,QString token="");
    void post(QString url, QByteArray param, QString token = "");
private:
    QNetworkAccessManager *m_pNetworkAccessManager;
    NetworkCookie* m_pCookie;
    bool m_bEnabelSSl;
    bool m_bAutoDelete;
private slots:
    void replyFinished(QNetworkReply *reply);
signals:
    void sglResponse(QString err, QString data);

};

HttpWork.cpp源文件

#include "HttpWork.h"
#include <QNetworkRequest>


HttpWork::HttpWork(QObject *parent, bool ssl , bool autoDelete)
    : QObject(parent)
    , m_bEnabelSSl(ssl)
    , m_bAutoDelete(autoDelete)
{
    m_pNetworkAccessManager = new QNetworkAccessManager(this);
    m_pCookie = new NetworkCookie(this);
    connect(m_pNetworkAccessManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(replyFinished(QNetworkReply*)));
}

HttpWork::~HttpWork()
{

}

void HttpWork::get(QString url,QString token)
{
    QNetworkRequest request(url);
    if (!token.isEmpty()) {
        request.setRawHeader("authorization", token.toStdString().c_str());;
    }

    request.setRawHeader("Content-Type", "application/json");
    m_pNetworkAccessManager->get(request);
}

void HttpWork::post(QString url, QByteArray param, QString token)
{
    QNetworkRequest request(url);
    if (!token.isEmpty()) {
        request.setRawHeader("authorization", token.toStdString().c_str());;
    }
    if (m_bEnabelSSl) {
        QSslConfiguration sslConfig = QSslConfiguration::defaultConfiguration();
        sslConfig.setPeerVerifyMode(QSslSocket::VerifyNone);
        sslConfig.setProtocol(QSsl::TlsV1_2);
        request.setSslConfiguration(sslConfig);
    }
    //设置cookie到浏览器

    m_pNetworkAccessManager->setCookieJar(m_pCookie);
    request.setRawHeader("Content-Type", "application/json");
    request.setRawHeader("Content-Type", "application/x-www-form-urlencoded");
    m_pNetworkAccessManager->post(request, param);
}

void HttpWork::replyFinished(QNetworkReply *reply)
{
    int code = -1;
    QVariant variant = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
    if (variant.isValid()){
        code =  variant.toInt();
    }

    QString err;
    QByteArray bytes;
    if(reply->error() == QNetworkReply::NoError) {
        QList<QNetworkCookie> cookies = m_pCookie->getCookies();
        for (int i = 0; i < cookies.length(); i++) {
            QNetworkCookie cookie = cookies.at(i);
            QString name = cookie.name();
            QString value  = cookie.value();            
        }
        bytes = reply->readAll();

    }
    else {
        err = reply->errorString()+"statusCode:"+code;
    }
    emit sglResponse(err, QString(bytes));
    if (m_bAutoDelete) {
        deleteLater();
    }
    
}

NetworkCookie.h头文件

#pragma once

#include <QNetworkCookieJar>
#include <QNetworkCookie>
class NetworkCookie : public QNetworkCookieJar
{
    Q_OBJECT

public:
    NetworkCookie(QObject *parent);
    ~NetworkCookie();
    QList<QNetworkCookie> getCookies();
    void setCookies(const QList<QNetworkCookie>& cookieList);
};

NetworkCookie.cpp源文件

#include "NetworkCookie.h"

NetworkCookie::NetworkCookie(QObject *parent)
    : QNetworkCookieJar(parent)
{
}

NetworkCookie::~NetworkCookie()
{
}

QList<QNetworkCookie> NetworkCookie::getCookies()
{
    return QNetworkCookieJar::allCookies();
}

void NetworkCookie::setCookies(const QList<QNetworkCookie>& cookieList)
{
    this->setAllCookies(cookieList);

}

需要http请求数据的时候调用:

void ServerAPI::login(QString address, int port, QString user, QString passwd)
{
    m_sAddress = address;
    m_nPort = port;
    m_sUser = user;
    m_sHost = QString("http%1://%2:%3").arg(m_nPort == 443 ? "s" : "").arg(address).arg(port);
    
    HttpWork* worker;
   
    worker = new HttpWork(this, m_nPort == 443);
   
    connect(worker, SIGNAL(sglResponse(QString, QString)), this, SLOT(sltOnReponseLogin(QString, QString)));
    QByteArray append = QString("type=1&account_or_mobile=%1&pwd_or_checkCode=%2").arg(user).arg(passwd).toUtf8();
    worker->post(m_sHost + "/admin-api/v1/user-manage/login", append);

}
void ServerAPI::sltOnReponseLogin(QString err, QString data)
{
    QString sErr = "";

    if (err.isEmpty()) {
        cJSON* jsData = cJSON_Parse(data.toStdString().c_str());
        if (jsData) {
            cJSON* pCode = cJSON_GetObjectItem(jsData, "code");
            cJSON* pData = cJSON_GetObjectItem(jsData, "data");
            if (pCode->valueint == 200)
            {
                m_sToken = cJSON_GetObjectItem(pData, "token")->valuestring;
            }
            else {
                cJSON* pError = cJSON_GetObjectItem(jsData, "error");
                sErr = pError->valuestring;
            }
        }
        cJSON_Delete(jsData);
    }
    else {
        sErr = err;
    }
    emit sglLoginResult(sErr.isEmpty() , sErr);
    if (sErr.isEmpty())
    {
        QTimer::singleShot(3000, this, SLOT(sltLoopTimeout()));   //这是一次性定时器到了定时间隔之后只发送一次信号槽函数只处理一次。初始化时不用等1分钟更新,3秒后就更新数据,不过值调用一次
        m_pLoopTimer->start(1000 * 60 * 1);   //1分钟更新
        //m_pLoopTimer->start(1000 * 10);   //10秒更新
    }
}

相关推荐