[原创]QT HTTP 通讯 使用方法

//////////////grabthread.h////////////////////
#ifndef GRABTHREAD_H
#define GRABTHREAD_H

#include <QThread>
class QNetworkAccessManager;
#include <QNetworkReply>

class GrabThread : public QThread
{
    Q_OBJECT
public:
    explicit GrabThread(QObject *parent = 0);
    void run();
    void saveToFile(QString&);

    bool runrun;

signals:

public slots:
    void slot_httpFinished();
    void slot_httpError(QNetworkReply::NetworkError);

private:
    QNetworkAccessManager* qnam;
    QNetworkReply* reply;
    QString query_word;
    bool is_init;
};

#endif // GRABTHREAD_H



//////////////grabthread.cpp////////////////////
#include <QtNetwork/QNetworkAccessManager>
#include <QtNetwork/QNetworkReply>
#include <QtNetwork/QNetworkRequest>
#include <QEventLoop>

GrabThread::GrabThread(QObject *parent) :
    QThread(parent),
    is_init(true)
{
}

void GrabThread::run()
{
    if (is_init)
    {
        qnam = new QNetworkAccessManager();
        is_init = false;
    }
    while(runrun)
    {
        startQuery("");
    }
}

void GrabThread::startQuery(QString redirect_url)
{
    QNetworkRequest request;
    QString url;
    // 如果是重定向请求, 则直接指向位置, 否则拼字符串
    if (redirect_url.length() != 0)
    {
        url = redirect_url;
    }else
    {
        url = "http://www.nuihq.com/" + query_word;
    }
    // 设定url
    request.setUrl(QUrl(url));
    // 设定请求头
    request.setRawHeader("Host", "www.nuihq.com");
    request.setRawHeader("User-Agent", "Mozilla/5.0 (X11; Linux x86_64; rv:7.0.1) Gecko/20100101 Firefox/7.0.1");
    request.setRawHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
    request.setRawHeader("Accept-Language", "zh-cn,zh;q=0.5");
    // TODO:使用gzip
    request.setRawHeader("Accept-Encoding", "deflate");
    request.setRawHeader("Accept-Charset", "utf-8;q=0.7,*;q=0.7");
    request.setRawHeader("Connection", "keep-alive");

    // 使用get方式发起请求
    reply = qnam->get(request);
    
/***************如果需要同步********************/
    qRegisterMetaType<QNetworkReply::NetworkError>
("QNetworkReply::NetworkError");
    QEventLoop loop; // 使用事件循环使得网络通讯同步进行
    connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
    connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), this,
            SLOT(slot_httpError(QNetworkReply::NetworkError)));
    loop.exec(); // 进入事件循环, 直到reply的finished()信号发出, 这个语句才能
                        //退出
    slot_httpFinished();
/**************************************/
/****************如果需要异步**********************/
    connect(reply, SIGNAL(finished()), this, SLOT(slot_httpFinished()));
    qRegisterMetaType<QNetworkReply::NetworkError>("QNetworkReply::NetworkError");
    connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), this,
            SLOT(slot_httpError(QNetworkReply::NetworkError)));
/**************************************/
}

void GrabThread::slot_httpFinished()
{
    int http_status = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();

    reply->close();
    reply->deleteLater();

    // 判断是否是重定向
    if (http_status == 302)
    {
        startQuery(reply->rawHeader("Location"));
    }else
    {
        QString reply_content = QString::fromUtf8(reply->readAll());
        if (reply->error() == QNetworkReply::NoError)
        {
            saveToFile(reply_content);
        }else
        {
            qDebug() << "ERROR:" << query_word << " CODE:" << reply->error();
        }
    }
}

void GrabThread::slot_httpError(QNetworkReply::NetworkError)
{

}

void GrabThread::saveToFile(QString & html_content)
{
    QFile file("html/" + query_word + ".html");
    file.open(QIODevice::WriteOnly);
    file.write(file_content.toUtf8());
    file.close();
}

你可能感兴趣的:(http,网络,qt,通讯)