Qt 5 HTTP 网络编程 (一)

原创
2018/04/26 16:46
阅读数 2W

新建项目

项目名称为:MyNetwork

编译器选为MinGW:

完成后新建类:MyNetwork

在配置文件中加入 "QT += network"

"mynetwork.h"头文件里加入以下行:

"mynetwork.cpp"文件里加入以下行:

"main.cpp"主函数里插入以下行:

完成后运行结果如下:

代码如下:

mynetwork.h

#ifndef MYNETWORK_H
#define MYNETWORK_H

#include <QObject>
#include <QNetworkAccessManager>

class MyNetwork : public QObject
{
    Q_OBJECT
public:
    explicit MyNetwork(QObject *parent = nullptr);
    void getHtml(QString url);

signals:

public slots:
    void replyFinished(QNetworkReply *reply);

private:
    QNetworkAccessManager *m_network;
};

#endif // MYNETWORK_H

mynetwork.cpp

#include "mynetwork.h"

#include <QDebug>
#include <QNetworkReply>

MyNetwork::MyNetwork(QObject *parent) : QObject(parent)
{
    m_network = new QNetworkAccessManager(this);
    QObject::connect(m_network, SIGNAL(finished(QNetworkReply*)),this ,SLOT(replyFinished(QNetworkReply*)));
}

void MyNetwork::getHtml(QString url)
{
    m_network->get(QNetworkRequest(QUrl(url)));
}

void MyNetwork::replyFinished(QNetworkReply *reply)
{
    qDebug() << reply->readAll();
}

main.cpp

#include <QCoreApplication>

#include "mynetwork.h"

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

    QString url = "http://10.10.50.206/users/sign_in";
    MyNetwork net;
    net.getHtml(url);

    return a.exec();
}

 

展开阅读全文
打赏
0
1 收藏
分享
加载中
更多评论
打赏
0 评论
1 收藏
0
分享
返回顶部
顶部