关闭

Qt网络编程之实例二POST方式

标签: qt编程网络stringattributes数据库服务器
10784人阅读 评论(3) 收藏 举报
分类:

       上一篇文章主要介绍了Qt网络编程的GET方式,这里再说一下POST方式。首先说一下自己的环境:

        主机:Win7;Web服务器:TomCat v7.x;数据库服务器:MySQL v5.x。

        主要是用Qt实现登录验证,后台使用servlet响应登录请求,查询后台数据库,是否为合法用户。相信大家明白了吧!我实现的就是客户端发出请求,服务器端在数据库中进行查询,如果查找到,则返回用户信息,如果没有找到,则返回0,首先贴一下效果图:

        1、在浏览器中测试:


         2、在Qt客户端中测试:


        这里贴一下Qt客户端的代码,服务器端的代码可详见另一篇博文:Android Tomcat 的应用之服务器部分

#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/");
    //QUrl url("http://www.google.com/ig/api?weather=wuhan");
    QUrl url("http://localhost:8080/WebRoot/servlet/LoginServlet");
    QByteArray append("username=admin&password=123456");
    //QNetworkReply* reply = nam->get(QNetworkRequest(url));
    QNetworkReply* reply = nam->post(QNetworkRequest(url), append);
    // 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
}

              好了,今天就到这吧

0
1

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:767672次
    • 积分:7290
    • 等级:
    • 排名:第3140名
    • 原创:70篇
    • 转载:14篇
    • 译文:22篇
    • 评论:128条
    我的新浪微博
    http://weibo.com/u/2001801991
    博客专栏
    最新评论