(QtNetwork)数据未返回/网络回复为空

时间:2013-10-14 17:02:58

标签: qt qnetworkaccessmanager qtnetwork qnetworkrequest

作为我之前问过的question的后续问题,我现在面临的问题是,即使请求的页面存在,下载的数据也是空的(至少从Web浏览器开始)。

我猜测数据实际上已下载导致调用fileDownloaded()的调试行,然后来自downloaded()的信号传递给SLOT(loadText(),然后打印到控制台每次点击按钮时都会"STRING: "

mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <string.h>
#include <iostream>
#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QByteArray>
#include <QTextCodec>
#include <QDebug>

using namespace std;

namespace Ui {
class MainWindow;
}

class DataFetch : public QObject
{
    Q_OBJECT

public:
    explicit DataFetch(QUrl url, QObject *parent=0);
    virtual ~DataFetch();

    QByteArray downloadedData() const;
signals:
    void downloaded();

public slots:
    void fileDownloaded(QNetworkReply* reply);

private:
    QNetworkAccessManager m_webManager;
    QByteArray m_downloaded;
};

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();
    DataFetch * m;

public slots:
    void btnClickHandler();

private slots:
    void loadText();

private:
    Ui::MainWindow *ui;
};





#endif // MAINWINDOW_H

mainwindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"


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

MainWindow::~MainWindow()
{
    delete ui;
}


DataFetch::DataFetch(QUrl url, QObject *parent):
    QObject(parent)
{
    connect(&m_webManager, SIGNAL(finished(QNetworkReply*)), SLOT(fileDownloaded(QNetworkReply*)));
    QNetworkRequest request(url);
    m_webManager.get(request);
}

DataFetch::~DataFetch() { }

void DataFetch::fileDownloaded(QNetworkReply *reply)
{
    QByteArray m_downloaded = reply->readAll();
    qDebug() << "received reply";
    reply->deleteLater();
    emit downloaded();
}

QByteArray DataFetch::downloadedData() const
{
    return m_downloaded;
}

void MainWindow::loadText()
{
    cout << "STRING: " << m->downloadedData().data() << endl;
    ui->lblText->setText(m->downloadedData());
}

void MainWindow::btnClickHandler()
{
    QUrl textURL = QUrl("http://192.168.2.7/index.html");
    m = new DataFetch(textURL, this);
    connect(m, SIGNAL(downloaded()), SLOT(loadText()));
}

main.cpp 与默认模板保持不变..

再次感谢您的帮助!

0 个答案:

没有答案