2
我在收集來自網絡請求的響應時遇到問題。 (因爲我是Qt新手)。Qt:如何獲得來自GET的響應?
爲什麼我有麻煩?
我有一個請求類,它發送請求並接收響應。但是我不能得到對請求對象的父對象的響應,因爲我必須等待來自處理響應的NetworkAccessMaanager的「完成」信號。
所以我處理「完成」插槽中的響應,但我無法將信息返回到持有請求對象的父主窗口。我怎樣才能做到這一點?
下面的代碼:
主要window.cpp:
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_buttonLogin_clicked()
{
request->sendRequest("www.request.com");
}
Request.cpp:
Request::Request()
{
oNetworkAccessManager = new QNetworkAccessManager(this);
QObject::connect(oNetworkAccessManager,SIGNAL(finished(QNetworkReply*)),this,SLOT(finishedSlot(QNetworkReply*)));
}
/*
* Sends a request
*/
QNetworkReply* Request::sendRequest(QString url)
{
QUrl httpRequest(url);
QNetworkRequest request;
request.setSslConfiguration(QSslConfiguration::defaultConfiguration()); // Set default ssl config
request.setUrl(httpRequest); // Set the url
QNetworkReply *reply = oNetworkAccessManager->get(QNetworkRequest(httpRequest));
return reply;
}
/*
* Runs when the request is finished and has received a response
*/
void Request::finishedSlot(QNetworkReply *reply)
{
// Reading attributes of the reply
// e.g. the HTTP status code
QVariant statusCodeV = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
// Or the target URL if it was a redirect:
QVariant redirectionTargetUrl =
reply->attribute(QNetworkRequest::RedirectionTargetAttribute);
// see CS001432 on how to handle this
// no error received?
if (reply->error() == QNetworkReply::NoError)
{
// Reading the data from the response
QByteArray bytes = reply->readAll();
QString jsonString(bytes); // string
bool ok;
QVariantMap jsonResult = Json::parse(jsonString,ok).toMap();
if(!ok)
{
qFatal("An error occured during parsing");
exit(1);
}
// Set the jsonResult
setJsonResult(jsonResult);
}
// Some http error received
else
{
// handle errors here
}
// We receive ownership of the reply object
// and therefore need to handle deletion.
delete reply;
}
/*
* Set the json result so that other functions can get it
*/
void Request::setJsonResult(QVariantMap jsonResult)
{
m_jsonResult = jsonResult;
}
/*
* Get the json result
* Return null if there is no result
*/
QVariantMap Request::getJsonResult()
{
return m_jsonResult;
}
的我怎麼能做到這一點任何想法?
在此先感謝!
你確定這是QNetworkReply發出finsished()?它看起來像是NetworkAccssManager這樣做。 – Ikky 2011-03-07 16:03:53
@lkky,看看我上面的代碼片段。 – Johnny 2011-03-08 08:14:54