• 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();
    } 
  • 相关阅读:
    AngularJS
    Java
    Java
    AngularJS
    Java
    Java
    AngularJS
    Java
    Debian
    Java
  • 原文地址:https://www.cnblogs.com/Malphite/p/14959929.html
Copyright © 2020-2023  润新知