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

1.Http客户端功能

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

2.支持连接超时处理.

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

2.源码

HttpClient.h

//HttpClient.h
 
#ifndef HTTPCLIENT_H
#define HTTPCLIENT_H
 
#include 
#include 
#include 
#include 
#include 
#include 
 
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(QNetworkReply *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::ProxyConnectionClosedError: return "ProxyConnectionClosedError";
        case QNetworkReply::ProxyNotFoundError: return "ProxyNotFoundError";
        case QNetworkReply::ProxyTimeoutError: 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";
    }
    return "UnknownError";
}
 
QString HttpClient::text() const
{
    return m_text;
}

3.使用方式

#include 
#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()<text();
    }
    else
    {
        qDebug()<errorCode();
    }
 
 
    return a.exec();
}

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

你可能感兴趣的:(QT实现自定义Http客户端的示例代码)