学校网站的建立/河北高端网站建设
上一篇文章主要介绍了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 codeQVariant 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 replyQByteArray bytes = reply->readAll(); // bytes//QString string(bytes); // stringQString string = QString::fromUtf8(bytes);ui->textBrowser->setText(string);}// Some http error receivedelse{// handle errors here}// We receive ownership of the reply object// and therefore need to handle deletion.reply->deleteLater();
#endif
}
好了,今天就到这吧