上一篇文章主要介紹了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}
好了,今天就到這吧