1. 程式人生 > >Qt實現Http通訊

Qt實現Http通訊

Qt學習需要http傳值,研究了好幾天終於可以了這裡只是一個最簡單的通訊,我的Qt是5.7.1

在Pro內新增 

QT       += network

widget.h中的原始碼

#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>
#include <QtNetwork>
#include <QNetworkAccessManager>
#include <QUrl>
#include <QNetworkRequest>
#include <QTextCodec>
#include <QNetworkReply>
#include <QDebug>
#include <QFileInfo>
#include <QEvent>
#include <QFile>
#include <QFileInfo>
#include <QHostInfo>
#include <QtWebEngineWidgets/QWebEnginePage>
#include <QByteArray>
#include <QTimer>

namespace Ui {
class Widget;
}

class Widget : public QWidget
{
    Q_OBJECT

public:
    explicit Widget(QWidget *parent = 0);
private:
    Ui::Widget *ui;
    QNetworkAccessManager *manager;
    QNetworkReply *reply;
    QUrl url;   //儲存網路地址
    QFile *file;//檔案指標
public slots:
    void replyFinished(QNetworkReply *);

};

#endif // WIDGET_H

widget.cpp中的原始碼如下

#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);

    manager = new QNetworkAccessManager(this);//新建QNetworkAccessManager物件

    connect(manager,SIGNAL(finished(QNetworkReply*)),
            this,SLOT(replyFinished(QNetworkReply*)));//關聯訊號和槽
    url = "http://123.160.246.110:8088/SMJ/ceshi";
    reply = manager->get(QNetworkRequest(url));
    //下面關聯訊號和槽
    connect(reply,SIGNAL(finished())
            ,this,SLOT(httpFinished()));//進行連結請求
    manager->get(QNetworkRequest(QUrl(url)));
}

void Widget::replyFinished(QNetworkReply *reply) //當回覆結束後
{
    QTextCodec *codec = QTextCodec::codecForName("utf8");
    //使用utf8編碼,這樣才可以顯示中文
    QString all = codec->toUnicode(reply->readAll());
    qDebug()<<"massr..."<<all;
    ui->textBrowser->setText(all);
}

這裡面的url為你要請求的程式碼的地址,
manager->get(QNetworkRequest(QUrl(url)));為顯示資料

結果如圖