Qt实现HTTP表单提交
2020-03-25 本文已影响0人
峰眼看世界
图片源自Qt官网
3. 在
image
4. 编写
5. 编写
6. 编写
Qt是一款跨平台的C++图形用户界面应用程序开发框架。就是可以拿它来开发桌面端程序。接触Qt已经是六年前的事情了,当初还是Qt 4.x,现在已经更新到Qt 5.x了。今天来分享下Qt下实现HTTP的表单提交,后台用Java提供一个简单的HTTP接口,完成整个前后台的交互。
1. 新建项目
首先新建一个Qt Widgets Application
的窗体程序,这里仅做简单演示,因此基类选择QDialog
。
今天的主题是HTTP post提交表单,因此要用到Qt的network
模块,在.pro
文件中加入该模块:
2. 项目配置
QT += core gui network
3. 在designer
界面设计器中进行界面设计
image
4. 编写dialog.h
头文件代码
#ifndef DIALOG_H
#define DIALOG_H
#include <QDialog>
#include <QtNetwork/QNetworkAccessManager>
namespace Ui {
class Dialog;
}
class Dialog : public QDialog
{
Q_OBJECT
public:
explicit Dialog(QWidget *parent = nullptr);
~Dialog();
private slots:
// http响应槽函数
void ReplaySlot(QNetworkReply *reply);
// 表单提交响应槽函数
void on_submitBtn_clicked();
private:
Ui::Dialog *ui;
QNetworkAccessManager *netAccessManager;
};
#endif // CREATE_CLASSROOM_DIALOG_H
5. 编写dialog.cpp
源文件代码
#include "dialog.h"
#include "ui_dialog.h"
#include <QNetworkReply>
Dialog::Dialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::Dialog)
{
ui->setupUi(this);
netAccessManager = new QNetworkAccessManager(this);
connect(netAccessManager, SIGNAL(finished(QNetworkReply *)), this, SLOT(ReplaySlot(QNetworkReply *)));
}
void Dialog::ReplaySlot(QNetworkReply *reply) {
int statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
qDebug() << "statusCode:" << statusCode;
}
Dialog::~Dialog()
{
delete ui;
if(netAccessManager != Q_NULLPTR) {
delete netAccessManager;
}
}
void Dialog::on_submitBtn_clicked()
{
QString name = ui->nameLineEdit->text();
qint64 startTime = ui->startDateTimeEdit->dateTime().toMSecsSinceEpoch();
qint64 endTime = ui->endDateTimeEdit->dateTime().toMSecsSinceEpoch();
int count = ui->cntSpinBox->value();
QString formInfo = QString("name=%1&startTime=%2&endTime=%3&count=%4")
.arg(name).arg(startTime).arg(endTime).arg(count);
QByteArray content = formInfo.toUtf8();
int contentLength = content.length();
QNetworkRequest netReq;
netReq.setUrl(QUrl("http://127.0.0.1:8080/apply"));
netReq.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
netReq.setHeader(QNetworkRequest::ContentLengthHeader, contentLength);
netAccessManager->post(netReq, content);
}
6. 编写Java
后台接口代码
@Slf4j
@Controller
@RequestMapping("")
public class ClassManagerController {
@PostMapping("apply")
@ResponseBody
public String createClassRoom(Map<String, Object> info) {
//TODO 其他业务操作
return "success";
}
}
至此,所有代码编写完成,首先把Java
程序运行,然后把Qt
程序运行,填写好表单,点击确定,即可完成一次HTTP
请求。
左手C++,右手Java,无不欢喜,哈哈~~