1. 程式人生 > 其它 >qt http get post實現

qt http get post實現

pro檔案

greaterThan(QT_MAJOR_VERSION, 4):QT += core network
QT -= gui

TARGET = httpget
CONFIG += console
CONFIG -= app_bundle

TEMPLATE = app

SOURCES += main.cpp \
    mynetworkobject.cpp

HEADERS += \
    mynetworkobject.h

main.cpp

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

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

    MyNetworkObject *networkObj = new MyNetworkObject();
    networkObj->get(url);

    return a.exec();
}

  

mynetworkobject.h

#ifndef MYNETWORKOBJECT_H
#define MYNETWORKOBJECT_H

#include <QObject>
#include <QNetworkAccessManager>
#include <QUrl>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QDebug>
//#include <QImageReader>

class MyNetworkObject : public QObject
{
    Q_OBJECT
public:
    explicit MyNetworkObject(QObject *parent = 0);
    void get(QUrl url);
public slots:
    void finishedSlot(QNetworkReply *reply);
signals:
private:
    QNetworkAccessManager *networkAccessManager;
};
#endif // MYNETWORKOBJECT_H

mynetworkobject.cpp

#include "mynetworkobject.h"
#include <QDebug>

MyNetworkObject::MyNetworkObject(QObject *parent) : QObject(parent) {
    networkAccessManager = new QNetworkAccessManager(this);
    QObject::connect(networkAccessManager, SIGNAL(finished(QNetworkReply *)), this, SLOT(finishedSlot(QNetworkReply *)));
}
void MyNetworkObject::get(QUrl url) {
    qDebug()<<"get "<<url;
    const QNetworkRequest request = QNetworkRequest(url);
    networkAccessManager->get(request);

}
void MyNetworkObject::finishedSlot(QNetworkReply *reply) {

    if(reply->error() == QNetworkReply::NoError) {;
        qDebug()<<"NoError";
        QByteArray buffer = reply->readAll();
        QString str = QString::fromUtf8(buffer);
        qDebug()<<str;
    } else {
        qDebug()<<reply->errorString();
    }
    reply->deleteLater();
}