Qt网络编程之实例一GET方式

      看了两天的Qt网络编程,其实主要就是看了看QNetworkAccessManagerQNetworkRequestQNetworkReply这三个类的主要内容。在之前,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 <QNetworkReply>
#include <QNetworkRequest>

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("http://www.hust.edu.cn/");
    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.

}

void MainWindow::finishedSlot(QNetworkReply *reply)
{
#if 1
     // 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)
     {
         // read data from QNetworkReply here

         // Example 1: Creating QImage from the reply
         //QImageReader imageReader(reply);
         //QImage pic = imageReader.read();

         // Example 2: Reading bytes form the reply
         QByteArray bytes = reply->readAll();  // bytes
         //QString string(bytes); // string
         QString string = QString::fromUtf8(bytes);

         ui->textBrowser->setText(string);
     }
     // Some http error received
     else
     {
         // handle errors here
     }

     // We receive ownership of the reply object
     // and therefore need to handle deletion.
     reply->deleteLater();
#endif
}

      好了,今天就到了!

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值