2012-10-18 110 views
2

我有一個類(RequestHandler),我從我的主要應用程序類調用以調用各種Web服務。一旦服務完成,類將信號發送回調用類來表示它已完成(可能帶有QString消息)。我有Signal在測試方法中工作,但QNetworkAccessManager根本不工作。我對QT和C++相當陌生。謝謝你的幫助。QT QNetworkAccessManager和信號

// RequestHandler.h

#ifndef REQUESTHANDLER_H_ 
#define REQUESTHANDLER_H_ 

#include <QNetworkAccessManager> 
#include <QUrl> 
#include <QNetworkRequest> 
#include <QNetworkReply> 
#include <QOBJECT> 
#include "MainAppClass.hpp" 

class RequestHandler : public QObject 
{ 
    Q_OBJECT 

public: 
    explicit RequestHandler(QObject *parent = 0); 
    void validateRegistration(QString reg); 
    void onStatusUpdateCompleted(); 
    void sayHi(); 

signals: 
    void sendSignal(QString txt); 
private: 
    QNetworkAccessManager* manager; 
    QObject* thisObj; 

public slots: 
    void onRequestCompleted(); 
}; 

#endif /* REQUESTHANDLER_H_ */ 

RequestHandler.cpp

#include "RequestHandler.h" 

RequestHandler::RequestHandler(QObject *parent) : QObject(parent) 
{ 
    thisObj= parent; 
} 
void RequestHandler::validateRegistration(QString reg) { 
    QNetworkRequest request; 
    request.setUrl(QUrl("the_registration_url")); 
    manager = new QNetworkAccessManager(); 
    QNetworkReply *reply = manager->get(request); 
    connect(reply, SIGNAL(finished()), this, SLOT(onRequestCompleted())); 
} 
void RequestHandler::onRequestCompleted() { 
    // not getting here at all 
} 
void RequestHandler::sayHi() 
{ 
    // this is working 
    QObject::connect(this, SIGNAL(sendSignal(QString)), thisCellCast, SLOT(recieveValue(QString))); 
    emit sendSignal("HERES THE SIGNAL"); 
} 

我調用這個類是這樣的:

// test slots and reg 
    RequestHandler rh(this); 
//working 
    rh.sayHi(); 
// not working 
    rh.validateRegistration("test"); 

感謝您的幫助。

回答

1

你通常應該使用QNetworkAccessManager通過連接到error()finished()信號,讓你在出錯通知發生。

validateRegistration()中構造QNetworkAccessManager對象是一個非常糟糕的主意,因爲它會導致內存泄漏,並且您只需要這種類型的一個對象。所以在RequestHandler的構造函數中做。

void RequestHandler::validateRegistration(QString reg) 
{ 
    QUrl url("the_registration_url"); 
    QNetworkRequest request(url); 
    QNetworkReply *reply = manager->get(request); 
    connect(reply, SIGNAL(finished()), SLOT(onRequestCompleted())); 
    connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), 
      SLOT(onError(QNetworkReply::NetworkError))); 
} 

void RequestHandler::onRequestCompleted() 
{ 
    qDebug() << "Request succeeded"; 
} 

void RequestHandler::onError(QNetworkReply::NetworkError code) 
{ 
    qError() << "Request failed with code " << code; 
} 

而且還要確保你有QApplication :: exec()調用某處,所以你有主要事件循環運行。