Qt使用HTTPS协议访问网站

所使用的Qt版本:5.14.0

可以先看一下这篇文章:《使用Qt访问网站的基本例子

注: 如果出现“qt.network.ssl: QSslSocket::connectToHostEncrypted: TLS initialization failed”这个错误,请查看这篇文章:《Qt TLS初始化失败解决办法

 

基于上面文章的例子进行更改:

#include <QCoreApplication>
#include "TestNet.h"

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    TestNet One;
    One.GetWeb();

    return a.exec();
}

//main.cpp
#include <QtNetwork>
#include <iostream>
#include <QFile>

class TestNet : public QObject
{
    Q_OBJECT
public:
    QNetworkAccessManager *m_manager = NULL;
    QNetworkRequest *m_request = NULL;

    //访问网站
    void GetWeb()
    {
        //建立新对象
        m_manager = new QNetworkAccessManager();
        m_request = new QNetworkRequest(QUrl("https://gitee.com/"));

        //设置SSL连接
        QSslConfiguration config;
        QSslConfiguration conf = m_request->sslConfiguration();
        conf.setPeerVerifyMode(QSslSocket::VerifyNone);
        conf.setProtocol(QSsl::TlsV1SslV3);
        m_request->setSslConfiguration(conf);

        //连接槽
        QObject::connect(m_manager,&QNetworkAccessManager::finished,this,&TestNet::GetWebFinished);

        //发送Get请求
        m_manager->get(*m_request);
    }

    //访问后做的操作
    void GetWebFinished(QNetworkReply *reply)
    {
        //转换为utf-8编码,这样就可以显示中文了
        QTextCodec *codec = QTextCodec::codecForName("utf8");
        QString getData = codec->toUnicode(reply->readAll());

        //输出文件
        QFile out_file("One.html");
        out_file.open(QIODevice::Text | QIODevice::WriteOnly);

        out_file.write(getData.toUtf8());

        out_file.close();
    }

};

//TestNet.h

 

posted @ 2020-04-29 19:54  NumPuppet  阅读(2655)  评论(0编辑  收藏  举报