开发者

QT实现自定义Http客户端的示例代码

开发者 https://www.devze.com 2022-12-03 11:06 出处:网络 作者: 音视频开发老舅
目录1.Http客户端功能2.源码HttpClient.hHttpClient.cpp3.使用方式1.Http客户端功能 1.支持get,post请求方式.
目录
  • 1.Http客户端功能
  • 2.源码
    • HttpClient.h
    • HttpClient.cpp
  • 3.使用方式

    1.Http客户端功能

    1.支持get,post请求方式.

    2.支持连接超时处理.

    3.支持网络错误,尝试重连.

    2.源码

    HttpClient.h

    //HttpClient.h
     
    #ifndef HTTPCLIENT_H
    #define HTTPCLIENT_H
     
    #include <QObject>
    #inclu开发者_JAV培训de <QNetworkAccessManager>
    #include <QNetworkReply>
    #include <QEventLoop>
    #include <QTimer>
    #include <QTextCodec>
     
    class HttpClient : public QObject
    {
        Q_OBJECT
    public:
        explicit HttpClient(QObject *parent = nullptr);
        ~HttpClient();
     
        static HttpClient *getInstance()
        {
            static HttpClient m_instance;
            return &m_instance;
        }
     
        bool get(QNetworkRequest request);
     
        bool post(QNetworkRequest request, const QByteArray &data);
     
        QString errorCode() const;
     
        QString text() const;
     
    private:
        void processReply(QNetworkReply *reply);
     
    private:
        QNetworkAccessManager		*m_networkAccessManager = nullptr;
        QNetworkReply::NetworkError  m_error;
        QString						 m_text; // 存放网络请求返回的文本字符串
        QString						 m_errorString;//存放错误信息
        int							 m_networkErrorRetry = 0;    // 网络错误重试次数
        QEventLoop					 m_eventLoop;
        QTimer                      *m_timer = nullptr;
        QByteArray				     m_data; // 存放网络请求返回的原始数据
    };
     
    #endif // HTTPCLIENT_H

    HttpClient.cpp

    #include "HttpClient.h"
     
    HttpClient::HttpClient(QObject *parent)
        : QObject(parent)
    {
        m_networkAccessManager = new QNetworkAccessManager(this);
     
        m_timer = new QTimer(this);
        m_timer->setInterval(3000);
        m_timer->setSingleShot(true);
        connect(m_timer, SIGNAL(timeout()), &m_eventLoop, SLOT(quit()));
    }
     
    HttpClient::~HttpClient()
    {
     
    }
     
     
    bool HttpClient::get(QNetworkRequest request)
    {
        QNetworkReply *reply;
        bool success = false;
        request.setPriority(QNetworkRequest::HighPriority);
        for(int i = 0 ; i < m_networkErrorRetry 编程客栈+ 1; i++)//
        {
            reply = m_networkAccessManager->get(request);
            processReply(reply);
            if (m_error == QNetworkReply::NoError)
            {
                success = true;
                break;
            }
        }
        return success;
    }
     
    bool HttpClient::post(QNetworkRequest request, const QByteArray &data)
    {
        QNetworkReply *reply;
        bool success = false;
        request.setPriority(QNetworkRequest::HighPriority);
        for (int i = 0; i < m_networkErrorRetry + 1; i++)
        {
            reply = m_networkAccessManager->post(request, data);
            processReply(reply);
            if (m_error == QNetworkReply::NoError)
            {
                success = true;
                break;
            }
        }
        return success;
    }
     
    void HttpClient::processReply(QNetworkRpythoneply *reply)
    {
        connect(reply, SIGNAL(finished()), &m_eventLoop, SLOT(quit()));
     
        m_text.clear();
        m_timer->start();
        m_eventLoop.exec();
     
        if (m_timer->isActive())
        {
            m_timer->stop();
     
            m_error = reply->error();
            m_errorString = reply->errorString();
            if (reply->bytesAvailable() > 0)
            {
                m_data = reply->readAll();
                QTextCodec *codec = QTextCodec::codecForhtml(m_data, QTextCodec::codecForName("utf-8"));
                if (codec)
                    m_text = codec->toUnicode(m_data);
            }
            else
            {
                m_data.clear();
                m_text.clear();
            }
        }
        else
        {
            reply->abort();
            m_error = QNetworkReply::TimeoutError;
        }
     
        delete reply;
    }
     
    QString HttpClient::errorCode() const
    {
        switch (m_error)
        {
            case QNetworkReply::NoError: return "NoError";
            case QNetworkReply::ConnectionRefusedError: return "ConnectionRefusedError";
            case QNetworkReply::RemoteHostClosedError: return "RemoteHostClosedError";
            case QNetworkReply::HostNotFoundError: return "HostNotFoundError";
            case QNetworkReply::TimeoutError: return "TimeoutError";
            case QNetworkReply::OperationCanceledError: return "OperationCanceledError";
            case QNetworkReply::SslHandshakeFailedError: return "SslHandshakeFailedError";
            case QNetworkReply::TemporaryNetworkFailureError: return "TemporaryNetworkFailureError";
            case QNetworkReply::ProxyConnectionRefusedError: return "ProxyConnectionRefusedError";
            case QNetworkReply::ProxyConnectionClo编程客栈sedError: return "ProxyConnectionClosedError";
            case QNetworkReply::ProxyNotFoundError: return "ProxyNotFoundError";
            case QNetworkReply::ProxyTimeout编程客栈Error: return "ProxyTimeoutError";
            case QNetworkReply::ProxyAuthenticationRequiredError: return "ProxyAuthenticationRequiredError";
            case QNetworkReply::ContentAccessDenied: return "ContentAccessDenied";
            case QNetworkReply::ContentOperationNotPermittedError: return "ContentOperationNotPermittedError";
            case QNetworkReply::ContentNotFoundError: return "ContentNotFoundError";
            case QNetworkReply::AuthenticationRequiredError: return "AuthenticationRequiredError";
            case QNetworkReply::ContentReSendError: return "ContentReSendError";
            case QNetworkReply::ProtocolUnknownError: return "ProtocolUnknownError";
            case QNetworkReply::ProtocolInvalidOperationError: return "ProtocolInvalidOperationError";
            case QNetworkReply::UnknownNetworkError: return "UnknownNetworkError";
            case QNetworkReply::UnknownProxyError: return "UnknownProxyError";
            case QNetworkReply::UnknownContentError: return "UnknownContentError";
            case QNetworkReply::ProtocolFailure: return "ProtocolFailure";
        }
        returhttp://www.devze.comn "UnknownError";
    }
     
    QString HttpClient::text() const
    {
        return m_text;
    }

    3.使用方式

    #include <QCoreApplication>
    #include "HttpClient.h"
     
    int main(int argc, char *argv[])
    {
        QCoreApplication a(argc, argv);
     
        QNetworkRequest request;
        request.setUrl(QUrl("http://www.baidu.com"));
        request.setRawHeader("Content-Type", "application/json");
        if(HttpClient::getInstance()->get(request))
        {
            qDebug()<<HttpClient::getInstance()->text();
        }
        else
        {
            qDebug()<<HttpClient::getInstance()->errorCode();
        }
     
     
        return a.exec();
    }

    以上就是QT实现自定义Http客户端的示例代码的详细内容,更多关于QT自定义Http客户端的资料请关注我们其它相关文章!

    0

    精彩评论

    暂无评论...
    验证码 换一张
    取 消

    关注公众号