看了两天的Qt网络编程,其实主要就是看了看QNetworkAccessManager、QNetworkRequest和QNetworkReply这三个类的主要内容。在之前,Qt网络编程主要是使用QHttp等类,但是现在在帮助手册中这些类已经标记为过时的,所以,现在用Qt编写网络程序最好还是使用上面的三个类,之前也说过,对于一个应用程序来说,一个QNetworkAccessManager已经足够了。不知道你有没有通过名字看出这三个类的联系呢?这里再贴一下三个类的官方说明,加强印象,也有助于大家对照接下来的示例看。
QNetworkAccessManager
QNetworkRequest
QNetworkReply
|
Allows the application to send network requests and receive replie
Holds a request to be sent with QNetworkAccessManager
Contains the data and headers for a request sent with QNetworkAccessManager
|
个人感觉三者关系可简单理解如下:
接下来就看一个示例,其实主要内容还是Nokia给的示例,但是源程序有错误之处,我这里进行修改了,这里先贴一下效果:
再来贴一下主要的代码,代码简单,一看就懂,呵呵:
-
#include "mainwindow.h"
-
#include "ui_mainwindow.h"
-
-
#include
-
#include
-
-
MainWindow::MainWindow(QWidget *parent) :
-
QMainWindow(parent),
-
ui(new Ui::MainWindow)
-
{
-
ui->setupUi(this);
-
-
nam = new QNetworkAccessManager(this);
-
QObject::connect(nam, SIGNAL(finished(QNetworkReply*)),
-
this, SLOT(finishedSlot(QNetworkReply*)));
-
}
-
-
MainWindow::~MainWindow()
-
{
-
delete ui;
-
}
-
-
void MainWindow::on_pushButton_clicked()
-
{
-
QUrl url("");
-
QNetworkReply* reply = nam->get(QNetworkRequest(url));
-
-
-
-
-
-
}
-
-
void MainWindow::finishedSlot(QNetworkReply *reply)
-
{
-
#if 1
-
-
-
QVariant statusCodeV =
-
reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
-
-
QVariant redirectionTargetUrl =
-
reply->attribute(QNetworkRequest::RedirectionTargetAttribute);
-
-
-
-
if (reply->error() == QNetworkReply::NoError)
-
{
-
-
-
-
-
-
-
-
QByteArray bytes = reply->readAll();
-
-
QString string = QString::fromUtf8(bytes);
-
-
ui->textBrowser->setText(string);
-
}
-
-
else
-
{
-
-
}
-
-
-
-
reply->deleteLater();
-
#endif
-
}
好了,今天就到了!
阅读(605) | 评论(0) | 转发(0) |