Qt 5 HTTP Network Programming (1)

New Project

The project name is: MyNetwork

The compiler is selected as MinGW:

After completion, create a new class: MyNetwork

Add "QT += network" to the configuration file

Add the following lines to the "mynetwork.h" header file:

Add the following lines to the "mynetwork.cpp" file:

Insert the following lines into the "main.cpp" main function:

After completion, the running result is as follows:

code show as below:

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();
}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324982924&siteId=291194637