在Qt中创建Http网络请求
文章信息
测试基于
SDK: Qt for S60 "Garden" pre-release
设备:: Nokia 5800 XpressMusic
兼容于
平台: S60 3rd Edition, FP1, FP2
S60 5th Edition
S60 5th Edition
平台安全性
需要的签名: Self-Signed
能力: NetworkServices
文章
关键词: QNetworkAccessManager, QUrl, QNetworkReply, QNetworkRequest
由 dougcn
在 07 Jun 2009 创建
最后由 hamishwillee
在 11 Oct 2012 编辑
Contents |
概述
此代码片段演示如何使用QNetworkAccessManager来发送HTTP请求到Internet。
注: 要想使用这段代码,你得在你的开发平台上安装Qt for Symbian。
头文件
#include <QNetworkAccessManager>
#include <QUrl>
#include <QNetworkRequest>
#include <QNetworkReply>
QNetworkAccessManager* nam;
Source
创建QNetworkAccessManager 并启动监听finished信号
nam = new QNetworkAccessManager(this);
QObject::connect(nam, SIGNAL(finished(QNetworkReply*)),
this, SLOT(finished(QNetworkReply*)));
HTTP GET请求
QUrl url("http://www.forum.nokia.wiki");
QNetworkReply* reply = nam->get(QNetworkRequest(url));
// NOTE: Store QNetworkReply pointer (maybe into caller).
// When this HTTP request is finished you will receive this same
// QNetworkReply as response parameter.
// By the QNetworkReply pointer you can identify request and response.
接收到QNetworkAccessManager::finished信号时,HTTP请求已完成。
void MyHttpEngine::finished(QNetworkReply* reply)
{
// NOTE: we receive ownership of of QNetworkReply* reply -parameter
// Reading attributes of the reply
QVariant statusCodeV =
reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
// "200 OK" received?
if (statusCodeV.toInt()==200)
{
// TODO: read data from QNetworkReply
// Example of creating QImage from the reply
QImageReader imageReader(reply);
QImage pic = imageReader.read();
// Example of reading bytes form the reply
QByteArray bytes = reply->readAll(); // bytes
QString string(bytes); // string
}
// Some http error or redirect
else
{
// TODO:
}
delete reply;
}
参看
- 更多信息,请看:QNetworkAccessManager
后置条件
HTTP 响应收到了。


Jwchen08 - 为什么在Symbian手机上不能运行
为什么这段代码我在Symbian手机得不到结果?同样的请求我在电脑上可以正常运行的jwchen08 12:22, 14 September 2011 (EEST)
Hamishwillee - Old article
The code should run on a computer as well. Note that this is an old article though.hamishwillee 04:51, 15 September 2011 (EEST)