QT实现上传多文件和Json数据的进度条
- 这里功能主要是实现上传多个文件和Json数据同时上传,并显示上传的进度
- 头文件:objectstorage.h
- 源文件:objectstorage.cpp
- HTTP 客户端代码头文件:http_request.h
- HTTP 客户端代码源文件:http_request.cpp
这里功能主要是实现上传多个文件和Json数据同时上传,并显示上传的进度
采用请求方式:POST
类名:ObjectStorage
头文件:objectstorage.h
#ifndef OBJECTSTORAGE_H
#define OBJECTSTORAGE_H#include <QWidget>
#include "http_request.h"
#include "qlistwidget.h"
#include "menu_control.h"namespace Ui {
class ObjectStorage;
}
class ObjectStorage : public QWidget
{Q_OBJECTQThread HttpObjSThread;
public:explicit ObjectStorage(QWidget *parent = nullptr);~ObjectStorage();//设置token和api url 并获取域名商列表void start_objectStorage();//设置disable选项框void set_checkbox_disabled(QString corporation,QString account_name,QString bucket_name);private:Ui::ObjectStorage *ui;//HTTP客户端Http_request *http_client;const QString api_url = Menu_control::init_maps["api_url"];const QString username=Menu_control::u_username;const QString token = Menu_control::u_token;const QList<qint32>permission_list = Menu_control::permission_list;//请求enum class BUTTON_CLICK{no_action,get_corporation_list,get_account_list,get_bucket_list,get_bucket_file_list,get_current_bucket_path_list,get_download_file, post_upload_file,put_mkdir_or_del};struct HTTP_QUEUE{BUTTON_CLICK action;qint32 queue_id;};QList<HTTP_QUEUE>http_queue;//cleanvoid clean_data();//搜索路径下的内容void current_bucket_path_list(QString path);//http请求队列qint32 get_queue_id();signals:void http_get(QString url,qint32 queue_id);void http_download(QString url, QString save_file_path, qint32 queue_id);//提交数据信号void http_put(QString url,QJsonObject data);//上传文件void http_upload(QString url,QJsonObject data);private slots://获取运营商下的所有账号void on_corporation_comboBox_activated(int index);//获取账号下的所有bucketvoid on_account_comboBox_activated(int index);//获取数据结束void http_get_finished(bool status,QJsonObject data);//提交数据请求结束void http_put_finished(bool status,QJsonObject data);//下载文件结束void http_download_or_upload_finished(bool status, QJsonObject data);//查询单个bucket下所有文件void on_current_bucket_comboBox_activated(int index);//复制源站链接void on_copy_source_link_pushButton_clicked();//复制加速站链接void on_copy_acclerate_link_pushButton_clicked();//返回上一层目录void on_previous_path_pushButton_clicked();//点击ListWidgetItems信号槽void click_items(QListWidgetItem *item);//下载文件void on_download_file_pushButton_clicked();//上传文件void on_upload_file_pushButton_clicked();//刷新当前路径文件void on_current_path_pushButton_clicked();//新建目录void on_mkdir_pushButton_clicked();//删除bucket对象void on_delete_bucket_object_pushButton_clicked();//下载上传进度条void update_progressbar(qint64 bytesReceived_or_sent, qint64 bytesTotal);
};#endif // OBJECTSTORAGE_H
源文件:objectstorage.cpp
#include "objectstorage.h"
#include "ui_objectstorage.h"
#include "ui_helper.h"
#include "core_common.h"
#include "base64.h"ObjectStorage::ObjectStorage(QWidget *parent): QWidget{parent},ui(new Ui::ObjectStorage)
{ui->setupUi(this);ui->save_file_label->setText(QDir::homePath()+QString("/Downloads/"));ui->handle_progressBar->setValue(0);http_client = new Http_request();http_client->set_exist_token(token);//建立信号槽//GET信号connect(this,&ObjectStorage::http_get,http_client,&Http_request::http_get);connect(http_client,&Http_request::http_get_finished,this,&ObjectStorage::http_get_finished); //PUT信号connect(this,&ObjectStorage::http_put,http_client,&Http_request::http_put);connect(http_client,&Http_request::http_put_finished,this,&ObjectStorage::http_put_finished);//下载connect(this,&ObjectStorage::http_download,http_client,&Http_request::http_download);connect(http_client,&Http_request::http_download_finished,this,&ObjectStorage::http_download_or_upload_finished);//上传connect(this,&ObjectStorage::http_upload,http_client,&Http_request::http_upload);connect(http_client,&Http_request::http_upload_finished,this,&ObjectStorage::http_download_or_upload_finished);//进度条connect(http_client,&Http_request::updateProgressBar,this,&ObjectStorage::update_progressbar);//线程开始http_client->moveToThread(&HttpObjSThread);//线程关闭connect(&HttpObjSThread,&QThread::finished,http_client,&QObject::deleteLater);//线程开始HttpObjSThread.start();//QListWidget信号槽connect(ui->object_listWidget,&QListWidget::itemClicked,this,&ObjectStorage::click_items);
}ObjectStorage::~ObjectStorage(){http_client = nullptr;delete http_client;HttpObjSThread.quit();HttpObjSThread.wait();delete ui;
}//获取随机请求id
qint32 ObjectStorage::get_queue_id(){return QRandomGenerator::global()->bounded(1, 9999999);
}//设置token和api url 并获取域名商列表
void ObjectStorage::start_objectStorage(){QByteArray byte_data = QString("{\"t_time\":%1,\"function_id\":%2,\"random_str\":\"%3\"}").arg(Core_common::get_timestamp(),QString::number(3),Core_common::get_random_str(15)).toLocal8Bit();QString data = MyBase64::get_base64_encode_2(byte_data.toHex());QtConcurrent::run([=]{HTTP_QUEUE action;qint32 queue_id = get_queue_id();action.action = BUTTON_CLICK::get_corporation_list;action.queue_id = queue_id;http_queue<<action;emit http_get(api_url+"api/cloud/oss?account_name="+data+"&common_area=3382210&lang=zh_cn",queue_id);});
}
//设置运营商,账户,bucket
void ObjectStorage::set_checkbox_disabled(QString corporation,QString account_name,QString bucket_name){ui->corporation_comboBox->addItem(corporation);ui->corporation_comboBox->setCurrentText(corporation);ui->corporation_comboBox->setDisabled(true);ui->account_comboBox->addItem("");ui->account_comboBox->addItem(account_name);ui->account_comboBox->setCurrentText(account_name);ui->account_comboBox->setDisabled(true);ui->current_bucket_comboBox->addItem("");ui->current_bucket_comboBox->addItem(bucket_name);ui->current_bucket_comboBox->setDisabled(true);ui->current_bucket_comboBox->setCurrentText(bucket_name);ui->current_path_lineEdit->setText("/");on_current_path_pushButton_clicked();
}// 运营商选项栏信号槽 ->查询运营商下所有账户
void ObjectStorage::on_corporation_comboBox_activated(int index)
{ui->account_comboBox->clear();ui->current_bucket_comboBox->clear();clean_data();if (index == 0){return ;}QByteArray byte_data = QString("{\"t_time\":%1,\"function_id\":%2,\"platform\":\"%3\",\"random_str\":\"%4\"}").arg(Core_common::get_timestamp(),QString::number(4),ui->corporation_comboBox->itemText(index),Core_common::get_random_str(15)).toLocal8Bit();QString data = MyBase64::get_base64_encode_2(byte_data.toHex());QtConcurrent::run([=]{HTTP_QUEUE action;qint32 queue_id = get_queue_id();action.action = BUTTON_CLICK::get_account_list;action.queue_id = queue_id;http_queue<<action;emit http_get(api_url+"api/cloud/oss?account_name="+data+"&common_area="+queue_id+"&lang=zh_cn",queue_id);});
}//获取账号下的所有bucket
void ObjectStorage::on_account_comboBox_activated(int index)
{ui->current_bucket_comboBox->clear();clean_data();if((index == 0) | (ui->corporation_comboBox->currentIndex() == 0) ){return;}QByteArray byte_data = QString("{\"t_time\":%1,\"function_id\":%2,\"platform\":\"%3\",\"account_name\":\"%4\",\"random_str\":\"%5\"}").arg(Core_common::get_timestamp(),QString::number(5),ui->corporation_comboBox->currentText(),ui->account_comboBox->itemText(index),Core_common::get_random_str(15)).toLocal8Bit();QString data = MyBase64::get_base64_encode_2(byte_data.toHex());QtConcurrent::run([=]{HTTP_QUEUE action;qint32 queue_id = get_queue_id();action.action = BUTTON_CLICK::get_bucket_list;action.queue_id = queue_id;http_queue<<action;emit http_get(api_url+"api/cloud/oss?account_name="+data+"&common_area=3382210&lang=zh_cn",queue_id);});
}//获取bucket下目录查询
void ObjectStorage::on_current_bucket_comboBox_activated(int index)
{clean_data();if(index == 0){return;}QByteArray byte_data = QString("{\"t_time\":%1,\"function_id\":%2,\"platform\":\"%3\",\"account_name\":\"%4\",\"bucket_name\":\"%5\",\"random_str\":\"%6\"}").arg(Core_common::get_timestamp(),QString::number(6),ui->corporation_comboBox->currentText(),ui->account_comboBox->currentText(),ui->current_bucket_comboBox->itemText(index),Core_common::get_random_str(15)).toLocal8Bit();QString data = MyBase64::get_base64_encode_2(byte_data.toHex());QtConcurrent::run([=]{HTTP_QUEUE action;qint32 queue_id = get_queue_id();action.action = BUTTON_CLICK::get_bucket_file_list;action.queue_id = queue_id;http_queue<<action;emit http_get(api_url+"api/cloud/oss?account_name="+data+"&common_area=3382210&lang=zh_cn",queue_id);});
}//清理数据
void ObjectStorage::clean_data(){ui->object_listWidget->clear();ui->current_bucket_location_label->clear();ui->current_path_lineEdit->clear();ui->copy_source_link_lineEdit->clear();ui->copy_accelerate_link_lineEdit->clear();ui->download_click_file_label->clear();ui->handle_progressBar->setValue(0);ui->upload_console_plainTextEdit->clear();
}//复制源站链接
void ObjectStorage::on_copy_source_link_pushButton_clicked()
{QClipboard *clip = QApplication::clipboard();clip->setText(ui->copy_source_link_lineEdit->text());
}//复制加速源链接
void ObjectStorage::on_copy_acclerate_link_pushButton_clicked()
{QClipboard *clip = QApplication::clipboard();clip->setText(ui->copy_accelerate_link_lineEdit->text());
}//返回上一层目录
void ObjectStorage::on_previous_path_pushButton_clicked()
{ui->download_click_file_label->clear();QString current_path = ui->current_path_lineEdit->text();if(current_path.isEmpty()){return;}if(current_path == "/"){UI_helper::showMessageBox("Warning","已是最顶层目录,\nThe currently is the topmost directory",2);return;}//查找倒数第二次出现所在的位置,字符串截断,截取到所在位置current_bucket_path_list(current_path.mid(0,(current_path.lastIndexOf("/",-2))+1));
}//点击ListWidget中单个items信号槽
void ObjectStorage::click_items(QListWidgetItem *item){QString item_name = item->text();if(item_name.contains("/")){QString current_path = ui->current_path_lineEdit->text();current_path+=item_name;current_bucket_path_list(current_path);}else{ui->download_click_file_label->setText(item_name);QString current_source_link = ui->copy_source_link_lineEdit->text();current_source_link = current_source_link.mid(0,(current_source_link.lastIndexOf("/",-1)+1));ui->copy_source_link_lineEdit->setText(current_source_link+item_name);QString current_accelerate_link = ui->copy_accelerate_link_lineEdit->text();current_accelerate_link = current_accelerate_link.mid(0,(current_accelerate_link.lastIndexOf("/",-1)+1));ui->copy_accelerate_link_lineEdit->setText(current_accelerate_link+item_name);}
}//搜索路径下的内容
void ObjectStorage::current_bucket_path_list(QString path){ui->object_listWidget->clear();ui->upload_console_plainTextEdit->clear();QByteArray byte_data = QString("{\"t_time\":%1,\"function_id\":%2,\"platform\":\"%3\",\"account_name\":\"%4\",\"prefix\":\"%5\",""\"bucket_name\":\"%6\",\"random_str\":\"%7\"}").arg(Core_common::get_timestamp(),QString::number(7),ui->corporation_comboBox->currentText(),ui->account_comboBox->currentText(),path,ui->current_bucket_comboBox->currentText(),Core_common::get_random_str(15)).toLocal8Bit();QString data = MyBase64::get_base64_encode_2(byte_data.toHex());QtConcurrent::run([=]{HTTP_QUEUE action;qint32 queue_id = get_queue_id();action.action = BUTTON_CLICK::get_current_bucket_path_list;action.queue_id = queue_id;http_queue<<action;emit http_get(api_url+"api/cloud/oss?account_name="+data+"&common_area=3382210&lang=zh_cn",queue_id);});
}//下载文件
void ObjectStorage::on_download_file_pushButton_clicked()
{if(ui->download_click_file_label->text().isEmpty()){UI_helper::showMessageBox("Warning","请选择文件再下载,\nPlease select file then click button",2);return;}QString file_path = ui->save_file_label->text()+ui->download_click_file_label->text();QFileInfo download_file = QFile(file_path);if(download_file.exists()){int status = UI_helper::showMessageBox("Warning","文件已存在是否覆盖,\nThe file exist AllowOverwrite on?",4,5000);if (status == 0){return;}}/*QByteArray byte_data = QString("{\"t_time\":%1,\"function_id\":%2,\"download_url\":\"%3\",\"random_str\":\"%4\"}").arg(Core_common::get_timestamp(),QString::number(8),ui->copy_source_link_lineEdit->text(),Core_common::get_random_str(15)).toLocal8Bit();QString data = MyBase64::get_base64_encode_2(byte_data.toHex());*/QtConcurrent::run([=]{HTTP_QUEUE action;qint32 queue_id = get_queue_id();action.action = BUTTON_CLICK::get_download_file;action.queue_id = queue_id;http_queue<<action;//emit http_get(api_url+"api/cloud/oss?account_name="+data+"&common_area=3382210&lang=zh_cn",queue_id);emit http_download(ui->copy_source_link_lineEdit->text(),file_path,queue_id);});
}//刷新当前路径文件
void ObjectStorage::on_current_path_pushButton_clicked()
{ui->download_click_file_label->clear();ui->handle_progressBar->setValue(0);QString current_path = ui->current_path_lineEdit->text();if (current_path.isEmpty()){UI_helper::showMessageBox("Warning","没有可刷新的数据,\nNo data to refresh",2,2000);return;}current_bucket_path_list(current_path);
}//上传文件
void ObjectStorage::on_upload_file_pushButton_clicked()
{if(ui->corporation_comboBox->currentIndex() == 0 || ui->account_comboBox->currentIndex() == 0 || ui->current_bucket_comboBox->currentIndex() == 0 ||ui->current_path_lineEdit->text().isEmpty()){UI_helper::showMessageBox("ParametersError","请选择要上传的用户名和仓库\nPlease select the username to upload and the repository selection",1);return;}//QString file_path = UI_helper::getOpenFileName("",QDir().homePath()+"/Desktop");QStringList file_path_list = QFileDialog::getOpenFileNames(this,"Select one or more files to open",QDir().homePath()+"/Desktop","");if(file_path_list.isEmpty()){ui->upload_console_plainTextEdit->appendPlainText("已取消Canceled");return;}ui->upload_console_plainTextEdit->clear();QJsonArray all_file_list;foreach (QString file_path, file_path_list) {all_file_list.append(QJsonValue::fromVariant(file_path));}ui->upload_console_plainTextEdit->appendPlainText("Waiting for...");//数据体QByteArray data_str = QString("{\"account_name\":\"%1\", \"t_time\":%2, \"function_id\":%3,\"platform\":\"%4\", \"bucket_name\":\"%5\",""\"prefix\":\"%6\",\"file_data\":\"%7\",\"secret_id\":\"%8\"}").arg(ui->account_comboBox->currentText(),Core_common::get_timestamp(),QString::number(1),ui->corporation_comboBox->currentText(),ui->current_bucket_comboBox->currentText(),ui->current_path_lineEdit->text(),"upload",Core_common::get_random_str(5)).toLocal8Bit();//加密QString data =MyBase64::get_base64_encode_2(data_str.toHex()) ;QJsonObject json_object;qint32 queue_id = get_queue_id();json_object.insert("file_list",all_file_list);json_object.insert("json_data",data);json_object.insert("queue_id",queue_id);QtConcurrent::run([=]{HTTP_QUEUE action;action.action = BUTTON_CLICK::post_upload_file;action.queue_id = queue_id;http_queue<<action;emit http_upload(api_url+"api/cloud/oss",json_object);});
}//新建目录
void ObjectStorage::on_mkdir_pushButton_clicked()
{if(ui->corporation_comboBox->currentIndex() == 0 || ui->account_comboBox->currentIndex() == 0 || ui->current_bucket_comboBox->currentIndex() == 0 ||ui->current_path_lineEdit->text().isEmpty()){UI_helper::showMessageBox("ParametersError","请选择用户名和仓库\nPlease select the username and the repository selection",1);return;}//输入目录名称bool is_confirm;QString dir_name;while(true){is_confirm = false;dir_name = QInputDialog::getText(this,"MKDIR","\t 请输入新目录的名称\t\n""\tPlease enter the new directory name\t\n",QLineEdit::Normal,"",&is_confirm/*,Qt::FramelessWindowHint*/);if(!is_confirm){ui->upload_console_plainTextEdit->appendPlainText("已取消Canceled");return;}if(dir_name.isEmpty()){ui->upload_console_plainTextEdit->appendPlainText("目录名称不允许为空The directory name cannot be empty");continue;}break;}QString jsonString = QString("[{\"file_name\":\"%1\",\"file_data\":\"\"}]").arg(dir_name+"/");//数据体QByteArray data_str = QString("{\"account_name\":\"%1\", \"t_time\":%2, \"function_id\":%3,\"platform\":\"%4\", \"bucket_name\":\"%5\",""\"prefix\":\"%6\",\"file_data\":%7,\"secret_id\":\"%8\"}").arg(ui->account_comboBox->currentText(),Core_common::get_timestamp(),QString::number(1),ui->corporation_comboBox->currentText(),ui->current_bucket_comboBox->currentText(),ui->current_path_lineEdit->text(),jsonString,Core_common::get_random_str(5)).toLocal8Bit();//加密QString data =MyBase64::get_base64_encode_2(data_str.toHex()) ;//qDebug()<<data;QJsonObject json_object;qint32 queue_id = get_queue_id();json_object.insert("json_data",data);json_object.insert("queue_id",queue_id);QtConcurrent::run([=]{HTTP_QUEUE action;action.action = BUTTON_CLICK::put_mkdir_or_del;action.queue_id = queue_id;http_queue<<action;emit http_put(api_url+"api/cloud/oss",json_object);});ui->upload_console_plainTextEdit->appendPlainText("Waiting for...");}//删除bucket对象
void ObjectStorage::on_delete_bucket_object_pushButton_clicked()
{if(ui->corporation_comboBox->currentIndex() == 0 || ui->account_comboBox->currentIndex() == 0 || ui->current_bucket_comboBox->currentIndex() == 0 ||ui->current_path_lineEdit->text().isEmpty()){UI_helper::showMessageBox("ParametersError","请选择用户名和仓库\nPlease select the username and the repository selection",1);return;}if (ui->save_file_label->text().isEmpty()){UI_helper::showMessageBox("EmptyError","没有可删除的文件\nPlease select file and the repository selection",1);return;}//输入目录名称bool is_confirm;while(true){is_confirm = false;QString password = QInputDialog::getText(this,"DeleteObjects","\t 请输入密码确认删除\t\n""\tPlease enter the password\t\n",QLineEdit::Normal,"",&is_confirm/*,Qt::FramelessWindowHint*/);if(!is_confirm){ui->upload_console_plainTextEdit->appendPlainText("已取消Canceled");return;}if(password.isEmpty() || password != "123qqq...A"){ui->upload_console_plainTextEdit->appendPlainText("删除文件"+ ui->download_click_file_label->text() + "密码不正确请重试The password incorrect");continue;}break;}//数据体QByteArray data_str = QString("{\"account_name\":\"%1\", \"t_time\":%2, \"function_id\":%3,\"platform\":\"%4\", \"bucket_name\":\"%5\",""\"prefix\":\"%6\",\"file_name\":\"%7\",\"secret_id\":\"%8\"}").arg(ui->account_comboBox->currentText(),Core_common::get_timestamp(),QString::number(9),ui->corporation_comboBox->currentText(),ui->current_bucket_comboBox->currentText(),ui->current_path_lineEdit->text(),ui->download_click_file_label->text(),Core_common::get_random_str(5)).toLocal8Bit();//加密//qDebug()<<data_str;QString data =MyBase64::get_base64_encode_2(data_str.toHex()) ;//qDebug()<<data;QJsonObject json_object;qint32 queue_id = get_queue_id();json_object.insert("json_data",data);json_object.insert("queue_id",queue_id);QtConcurrent::run([=]{HTTP_QUEUE action;action.action = BUTTON_CLICK::put_mkdir_or_del;action.queue_id = queue_id;http_queue<<action;emit http_put(api_url+"api/cloud/oss",json_object);});ui->upload_console_plainTextEdit->appendPlainText("Waiting for...");
}//上传下载进度条
void ObjectStorage::update_progressbar(qint64 bytesReceived_or_sent, qint64 bytesTotal){ui->handle_progressBar->setValue(bytesReceived_or_sent *100/bytesTotal);
}//Http download or upload 下载或上传文件结束
void ObjectStorage::http_download_or_upload_finished(bool status, QJsonObject data){qint32 queue_id = data.value("queue_id").toInt();qint32 index = 0;BUTTON_CLICK funcId = BUTTON_CLICK::no_action;for(int i =0;i<http_queue.size();i++) {if(queue_id == http_queue.at(i).queue_id){funcId = http_queue.at(i).action;index = i;break;}}//移除当前请求成员http_queue.removeAt(index);if (BUTTON_CLICK::no_action == funcId){return;}if (status){QString message = data.value("Data").toString();if (BUTTON_CLICK::post_upload_file == funcId){ui->upload_console_plainTextEdit->appendPlainText(ui->download_click_file_label->text()+" "+ message);UI_helper::showMessageBox("Success","上传成功 \nUpload file Success\n",0);on_current_path_pushButton_clicked();}else{ui->upload_console_plainTextEdit->appendPlainText(ui->download_click_file_label->text()+": 下载成功 Download Success");UI_helper::showMessageBox("Success","下载成功\n Download file Success\n",0,1500);}}else{QString message = data.value("Error").toString();if (BUTTON_CLICK::post_upload_file == funcId){UI_helper::showMessageBox("Failed","上传文件Faild \n"+message,1);ui->upload_console_plainTextEdit->appendPlainText(ui->download_click_file_label->text()+" "+message);}else{UI_helper::showMessageBox("Failed","下载失败Faild \n"+message,1);ui->upload_console_plainTextEdit->appendPlainText(ui->download_click_file_label->text()+": 下载失败 Faild " +message);}}
}//http geg获取数据结束
void ObjectStorage::http_get_finished(bool status,QJsonObject data){qint32 queue_id = data.value("queue_id").toInt();qint32 index = 0;BUTTON_CLICK funcId = BUTTON_CLICK::no_action;for(int i =0;i<http_queue.size();i++) {if(queue_id == http_queue.at(i).queue_id){funcId = http_queue.at(i).action;index = i;break;}}//移除当前请求成员http_queue.removeAt(index);if (BUTTON_CLICK::no_action == funcId){return;}if(status){QJsonArray data_array;data_array = data.value("Data").toArray();//qDebug()<<data_array;if(data_array.isEmpty()){UI_helper::showMessageBox("success","数据为空... \nData was Empty \n",3,2000);if (BUTTON_CLICK::get_bucket_file_list == funcId){ui->current_bucket_location_label->setText(data.value("location").toString()); }else if(BUTTON_CLICK::get_current_bucket_path_list == funcId){ui->current_path_lineEdit->setText(data.value("current_path").toString());}return;}switch (funcId) {//获取运营商case BUTTON_CLICK::get_corporation_list:for (int i=0;i<data_array.count();i++){QJsonObject obj = data_array[i].toObject();//qDebug()<<data_array[i];for (int key=0;key<obj.count();key++){std::string obj_key = obj.keys().at(key).toStdString();QString obj_value = obj.value(obj.keys().at(key)).toString();if(obj_key == "platform")ui->corporation_comboBox->addItem(obj_value);elsecontinue;}}break;//获取运营商下所有账号case BUTTON_CLICK::get_account_list:ui->account_comboBox->clear();ui->account_comboBox->addItem("");for (int i=0;i<data_array.count();i++){QJsonObject obj = data_array[i].toObject();for (int key=0;key<obj.count();key++){std::string obj_key = obj.keys().at(key).toStdString();QString obj_value = obj.value(obj.keys().at(key)).toString();if(obj_key == "account_name")ui->account_comboBox->addItem(obj_value);elsecontinue;//ui->object_listWidget->itemWidget(QListWidgetItem(""))}//rowcount++;}break;//获取账号下所有bucketcase BUTTON_CLICK::get_bucket_list:ui->current_bucket_comboBox->clear();ui->current_bucket_comboBox->addItem("");for (int i=0;i<data_array.count();i++){QJsonObject obj = data_array[i].toObject();for (int key=0;key<obj.count();key++){std::string obj_key = obj.keys().at(key).toStdString();QString obj_value = obj.value(obj.keys().at(key)).toString();if(obj_key == "bucket_name")ui->current_bucket_comboBox->addItem(obj_value);elsecontinue;//ui->object_listWidget->itemWidget(QListWidgetItem(""))}//rowcount++;}break;//获取bucket当前目录的所有文件和目录case BUTTON_CLICK::get_bucket_file_list:ui->current_bucket_location_label->setText(data.value("location").toString());ui->copy_accelerate_link_lineEdit->setText(data.value("accelerate_link").toString());ui->copy_source_link_lineEdit->setText(data.value("source_link").toString());ui->current_path_lineEdit->setText(data.value("current_path").toString());for (int i=0;i<data_array.count();i++){QJsonObject obj = data_array[i].toObject();QString obj_name = obj.value("obj_name").toString();QString obj_type = obj.value("type").toString();QListWidgetItem *obj_item = new QListWidgetItem();if(obj_type == "dir"){obj_item->setText(obj_name);obj_item->setForeground(QBrush(Qt::blue));}else{obj_item->setText(obj_name);}ui->object_listWidget->addItem(obj_item);}break;//获取bucket当前指定目录的所有文件和目录case BUTTON_CLICK::get_current_bucket_path_list:ui->current_bucket_location_label->setText(data.value("location").toString());ui->copy_accelerate_link_lineEdit->setText(data.value("accelerate_link").toString());ui->copy_source_link_lineEdit->setText(data.value("source_link").toString());ui->current_path_lineEdit->setText(data.value("current_path").toString());for (int i=0;i<data_array.count();i++){QJsonObject obj = data_array[i].toObject();QString obj_name = obj.value("obj_name").toString();QString obj_type = obj.value("type").toString();QListWidgetItem *obj_item = new QListWidgetItem();if(obj_type == "dir"){obj_item->setText(obj_name);obj_item->setForeground(QBrush(Qt::blue));}else{obj_item->setText(obj_name);}ui->object_listWidget->addItem(obj_item);}break;default:break;}}else{if(data.isEmpty()){UI_helper::showMessageBox("NetworkError","Connection timeout\n",1);}else{UI_helper::showMessageBox("ServiceError",data.value("Error").toString()+"\n",1);}}
}//http put 提交数据请求结束
void ObjectStorage::http_put_finished(bool status,QJsonObject data){qint32 queue_id = data.value("queue_id").toInt();qint32 index = 0;BUTTON_CLICK funcId = BUTTON_CLICK::no_action;QString message;for(int i =0;i<http_queue.size();i++) {if(queue_id == http_queue.at(i).queue_id){funcId = http_queue.at(i).action;index = i;break;}}//移除当前请求成员http_queue.removeAt(index);if (BUTTON_CLICK::no_action == funcId){return;}if(status){message = data.value("Data").toString();switch (funcId) {//上传文件case BUTTON_CLICK::put_mkdir_or_del:on_current_path_pushButton_clicked();break;default:break;}if(message.isEmpty()){UI_helper::showMessageBox("SUCCESS",Core_common::get_current_time()+"\n 提交成功! \nData is submitted successfully \n\n ",3,1500);}else{UI_helper::showMessageBox("SUCCESS",Core_common::get_current_time()+"\n提交成功! \n"+message+"\nData is submitted successfully \n\n ",3,1500);}}else{message = data.value("Error").toString();UI_helper::showMessageBox("SubmitError",Core_common::get_current_time()+" \n"+message+"\nData submission failure \n\n ",1);}ui->upload_console_plainTextEdit->appendPlainText(message);
}
HTTP 客户端代码头文件:http_request.h
#ifndef HTTP_REQUEST_H
#define HTTP_REQUEST_H#include <QObject>
#include <QJsonObject>
#include <QJsonDocument>
#include <QJsonArray>
#include <QNetworkRequest>
#include <QNetworkAccessManager>
#include <QEventLoop>
#include <QNetworkReply>
#include <QDateTime>
#include <QTimer>
#include <QRandomGenerator>
#include <QHttpMultiPart>class Http_request : public QObject
{Q_OBJECT
public:explicit Http_request(QObject *parent = nullptr);~Http_request();//接收已存在的Tokenvoid set_exist_token(QString token);//获取存在的token值const QString get_exist_token();public slots://web接口网络连通性检测\版本\验证锁QJsonObject http_signal_check(QString url_str,QJsonObject data);//获取web接口TOKENvoid get_web_api_token(QString username,QString password,QString url ="",QString verify_code=NULL);//Get方法void http_get(QString url,const qint32 queue_id=0);//POS方式提交请求void http_post(QString url,QJsonObject data);//PUT方式提交请求void http_put(QString url,QJsonObject data);//从github获取地址QJsonObject http_get_github_data(QString url_str);//发起其他网站get请求void http_other_get(QString url,const qint32 queue_id);//发起get下载void http_download(QString url,QString save_file_path, const qint32 queue_id);//发起POST上传文件void http_upload(QString url,QJsonObject data);//向其他网站发起post请求void http_other_post(QString url,QJsonObject data,QMap<QString,QString>set_raw_headers);//Jenkins 构建void http_post_jenkins(QString url,QJsonObject data);private:enum class HttpAction {no_action,get_token_action,http_get,http_other_get,http_post,http_post_jenkins,http_other_post,http_put,http_downalod,http_upload,};struct ACTION_QUEUE{HttpAction action;qint32 queue_id = 0;QString mark ="";};QString token;QNetworkAccessManager * http;//QEventLoop event_loop;//http执行的动作QList<ACTION_QUEUE>access_queue;//http请求QNetworkRequest request;signals://获取Token结束void getToken_finished(bool gotToken_ok,QJsonArray data);//api接口连通性检测void signal_check_finished(bool status,QJsonObject data);//获取数据列表结束//void http_get_list_finished(bool status,QJsonObject data);//get获取数据结束void http_get_finished(bool status,QJsonObject data);//提交POST请求void http_post_finished(bool post_status,QJsonObject data);//提交PUT请求void http_put_finished(bool post_status,QJsonObject data);//Jenkins POST构建void http_post_jenkins_finished(bool post_status,QJsonObject data);//发起其他网站GET请求void http_other_get_finished(bool status,QJsonObject data);//download结束void http_download_finished(bool status,QJsonObject data);//upload文件结束void http_upload_finished(bool status,QJsonObject data);//发起其他网站POST请求结束void http_other_post_finished(bool status,QJsonObject data);//处理进度条void updateProgressBar(qint64 bytesReceived_or_sent,qint64 bytesTotal);
private://设置请求头void set_request_header();//生成错误响应状态码QJsonObject generateErrorResponse(int code, const QString& errorMessage);private slots:void http_finished(QNetworkReply* reply);
};#endif // HTTP_REQUEST_H
HTTP 客户端代码源文件:http_request.cpp
#include "http_request.h"
#include "encrypt/base64.h"
#include "encrypt/des.h"
#include <QMessageBox>
#include <QFile>
#include <QFileInfo>
#include <QNetworkConfigurationManager>Http_request::Http_request(QObject *parent): QObject{parent}
{http = new QNetworkAccessManager(this);//connect(http , &QNetworkAccessManager::finished, &event_loop, &QEventLoop::quit);connect(http , &QNetworkAccessManager::finished,this,&Http_request::http_finished);
}Http_request::~Http_request(){delete http;
}//接收已存在的Token
void Http_request::set_exist_token(QString exist_token){if(token.isEmpty()){token = exist_token;return;}
}//获取已存在的token
const QString Http_request::get_exist_token(){if(token.isEmpty()){return QString();}return token;
} http 请求结束,解析数据 //
/// \brief Http_request::http_finished
/// \param reply
///
void Http_request::http_finished(QNetworkReply* reply){//获取字节流QByteArray response_data;QString type = reply->property("type").toString();qint32 id = reply->property("id").toInt();qint32 queue_id = reply->property("queue_id").toInt();qint32 index=0;QString mark;HttpAction http_action =HttpAction::no_action ;for(int i =0;i<access_queue.size();i++) {if(queue_id == access_queue.at(i).queue_id){http_action = access_queue.at(i).action;mark = access_queue.at(i).mark;index = i;break;}}access_queue.removeAt(index);if (HttpAction::no_action == http_action){return;}QJsonObject object;object.insert("id",id);object.insert("type",type);object.insert("queue_id",queue_id);if (reply->error() == QNetworkReply::NoError){QVariant contentType = reply->header(QNetworkRequest::ContentTypeHeader);response_data = reply->readAll();reply->deleteLater();reply = nullptr;//返回状态码// qDebug()<<reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).value<int>();//判断如果是获取Token无法访问测直接退出程序if(response_data.isEmpty() && (HttpAction::get_token_action == http_action) ){QMessageBox msgBox;msgBox.setText("找不到 google.com 服务器 IP 地址。\n1.检查网络连接 \n""2.检查代理服务器、防火墙和 DNS 配置\n""The server IP address for google.com cannot be found\n\nERR_NAME_NOT_RESOLVED...");msgBox.exec();exit(-1);}//判断服务器是否返回的格式if (!contentType.isNull()) {if (contentType.toString().contains("application/json")) {QJsonParseError json_error;// JSON 文档为对象QJsonDocument document = QJsonDocument::fromJson(response_data, &json_error);//判断如果未发生错误、或doucment//是否包含一个数组或一个对象,使用 isArray() 和 isObject()if (document.isNull() || (json_error.error != QJsonParseError::NoError)) {qDebug()<<"Web API callback data error"<<Qt::endl;object.insert("Error",QString(response_data));switch(http_action){case HttpAction::no_action:break;case HttpAction::get_token_action:emit getToken_finished(false,QJsonArray());break;case HttpAction::http_get:emit http_get_finished(false,object);break;case HttpAction::http_post:emit http_post_finished(false,object);break;case HttpAction::http_put:emit http_put_finished(false,object);break;case HttpAction::http_other_get:emit http_other_get_finished(false,object);break;case HttpAction::http_post_jenkins:emit http_post_jenkins_finished(false,object);break;case HttpAction::http_other_post:emit http_other_post_finished(false,object);default:break;}return;}//qDebug() << "The data is JSON";// 转化为对象object = document.object();object.insert("id",id);object.insert("type",type);object.insert("queue_id",queue_id);} else {qDebug() << "The data is not JSON"<<" Content-Type: "<<contentType.toString();}} else {qDebug() << "No Content-Type set by server";}switch(http_action){//登录case HttpAction::get_token_action:if (object.contains("Code")) {//判断是否成功获取返回200成功 其他错误if(object.value("Code") == 200){QJsonValue token_value = object.value("Data")["token"];QJsonArray permission_array = object.value("Data")["permission_list"].toArray();QString token_str = token_value.toString();//token加密串解密QString currently_time =QString::number(QDateTime::currentDateTime().toSecsSinceEpoch());token = MyBase64::get_base64_encode(QString(token_str)+"*"+currently_time+"*"+"base64en");emit getToken_finished(true,QJsonArray()<<token<<permission_array);break;}else if(object.value("Code") == 409){QMessageBox msgBox;msgBox.setText(object.value("Error").toString());msgBox.exec();exit(409);}else{emit getToken_finished(false,object.value("Error").toArray());break;}}emit getToken_finished(false,QJsonArray());break;//http请求case HttpAction::http_get:if (object.contains("Code")) {//判断是否成功获取返回200成功 其他错误if(object.value("Code") == 200){emit http_get_finished(true,object);break;}else if(object.value("Code") == 409){QMessageBox msgBox;msgBox.setText(object.value("Error").toString());msgBox.exec();exit(409);}else{emit http_get_finished(false,object);break;}}emit http_get_finished(false,object);break;//其他网站get数据case HttpAction::http_other_get:object.insert("Data","Success");emit http_other_get_finished(true,object);break;//http post请求case HttpAction::http_post:if (object.contains("Code")) {//判断是否提交成功返回200成功 其他错误if(object.value("Code") == 200){emit http_post_finished(true,object);}else if(object.value("Code") == 409){QMessageBox msgBox;msgBox.setText(object.value("Error").toString());msgBox.exec();exit(409);}else{emit http_post_finished(false,object);}break;}object.insert("Error","ERR_NAME_NOT_RESOLVED");emit http_post_finished(false,object);break;//http post_jenkins请求case HttpAction::http_post_jenkins:if (object.contains("Code")) {//判断是否提交成功返回200成功 其他错误if(object.value("Code") == 200){QJsonValue data_value = object.value("Data");if(!data_value.isNull() && data_value.isArray()){emit http_post_jenkins_finished(true, object);break;}emit http_post_jenkins_finished(true,QJsonObject());break;}else if(object.value("Code") == 409){QMessageBox msgBox;msgBox.setText(object.value("Error").toString());msgBox.exec();exit(409);}else{emit http_post_jenkins_finished(false,object);break;}}emit http_post_jenkins_finished(false,QJsonObject());break;//其他网站post数据case HttpAction::http_other_post:emit http_other_post_finished(true,object);break;//http put请求case HttpAction::http_put:if (object.contains("Code")) {//判断是否提交成功返回200成功 其他错误if(object.value("Code") == 200){emit http_put_finished(true, object);}else if(object.value("Code") == 409){QMessageBox msgBox;msgBox.setText(object.value("Error").toString());msgBox.exec();exit(409);}else{emit http_put_finished(false,object);}break;}object.insert("Error","ERR_NAME_NOT_RESOLVED");emit http_put_finished(false,object);break;//下载文件case HttpAction::http_downalod:if (! mark.isEmpty()){QFile download_file = QFile(mark);if (download_file.open(QIODevice::ReadWrite | QIODevice::Truncate)){download_file.write(response_data);emit http_download_finished(true,object);}else{object.insert("Error","Writing file faild,Permission denial");emit http_download_finished(false,object);break;}}object.insert("Error","File path is empty");emit http_download_finished(false,object);break;//上传文件case HttpAction::http_upload:if (object.contains("Code")) {//判断是否提交成功返回200成功 其他错误if(object.value("Code") == 200){emit http_upload_finished(true, object);}else if(object.value("Code") == 409){QMessageBox msgBox;msgBox.setText(object.value("Error").toString());msgBox.exec();exit(409);}else{emit http_upload_finished(false,object);}break;}object.insert("Error","data formatting error");emit http_upload_finished(false,object);break;default:break;}}else{if(HttpAction::get_token_action == http_action ){QMessageBox msgBox;msgBox.setText("找不到 google.com 服务器 IP 地址。\n1.检查网络连接 \n""2.检查代理服务器、防火墙和 DNS 配置\n""The server IP address for google.com cannot be found\n\nERR_NAME_NOT_RESOLVED...");msgBox.exec();exit(-1);}//添加错误object.insert("Error",reply->errorString());switch(http_action){//http请求case HttpAction::http_get:emit http_get_finished(false,object);break;//其他网站get数据case HttpAction::http_other_get:emit http_other_get_finished(false,object);break;//http post请求case HttpAction::http_post:emit http_post_finished(false,object);break;//http post_jenkins请求case HttpAction::http_post_jenkins:emit http_post_jenkins_finished(false,object);break;//其他网站post数据case HttpAction::http_other_post:emit http_other_post_finished(false,object);break;//http put请求case HttpAction::http_put:emit http_put_finished(false,object);break;//下载文件case HttpAction::http_downalod:emit http_download_finished(false,object);break;//上传文件case HttpAction::http_upload:emit http_upload_finished(false,object);break;default:break;}qDebug()<<"Network Error: "<<reply->errorString();reply->deleteLater();}
} 公共请求头
/// \brief Http_request::set_request_header
///
void Http_request::set_request_header(){//设置头部信息request.setRawHeader("Content-Type","application/json");//请求的数据头部//request.setRawHeader("Content-Type","*/*");//请求的数据头部//request.setRawHeader("Content-Type","application/x-www-form-urlencoded");//求的数据头部request.setRawHeader("Accept","*/*"); //数据头部//request.setRawHeader("Accept-Charset","GBK,utf-8;q=0.7,*;q=0.3;iso-8859-1;q=0.5");//request.setRawHeader("Accept-Encoding","gzip, deflate, br");//request.setRawHeader("Accept-Language","zh-CN,zh;q=0.9,en;q=0.8,en-US;q=0.7");request.setRawHeader("Access-Control-Allow-Headers","*");request.setRawHeader("Cache-Control","no-cache");request.setRawHeader("Connection","keep-alive");//request.setRawHeader("Host","ptlogin2.qq.com");request.setRawHeader("User-Agent","Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.62 Safari/537.36");
}/ 请求获取token
/// \brief Http_request::get_web_api_token
/// \param username
/// \param password
/// \param url_str
/// \param verify_code
///
void Http_request::get_web_api_token(QString username,QString password,QString url_str,QString verify_code){//设置urlrequest.setUrl(QUrl(url_str+"api/token"));//设置公共请求头set_request_header();QString currently_time =QString::number(QDateTime::currentDateTime().toSecsSinceEpoch());QString data_str = QString("{\"username\":\"%1\",\"password\":\"%2\",\"t_time\":%3,\"verify_code\":\"%4\"}").arg(username,MyBase64::get_base64_encode(password),currently_time,"base64");DES des;QByteArray hex_str = des.des_encrypt_encode_pkcs7(data_str,"jsldljsdfkjd3443903jfDAB9390J");QString data =MyBase64::get_base64_encode(hex_str.toHex()) ;//封装为JSON格式QJsonObject json_object;json_object.insert("secret_key",data);QJsonDocument json_doc;json_doc.setObject(json_object);QByteArray bytes_data = json_doc.toJson(QJsonDocument::Compact);QEventLoop event_loop;QTimer::singleShot(3000, &event_loop, &QEventLoop::quit);// 设置超时时间为3秒QNetworkReply *getReply =http->post(request,bytes_data);ACTION_QUEUE action;qint32 queue_id = QRandomGenerator::global()->bounded(100000, 999999);action.action = HttpAction::get_token_action;action.queue_id = queue_id;getReply->setProperty("queue_id",queue_id);access_queue<<action;event_loop.exec();
}/// GET 请求获取数据 /
void Http_request::http_get(QString url_str, qint32 queue_id){if(token.isEmpty()){qDebug()<<"token is empty"<<Qt::endl;return;}//设置urlrequest.setUrl(QUrl(url_str));//设置公共请求头set_request_header();request.setRawHeader("Authorization",token.toLocal8Bit());QEventLoop event_loop;QTimer::singleShot(3000, &event_loop, &QEventLoop::quit);QNetworkReply *getReply = http->get(request);getReply->setProperty("type", "get");ACTION_QUEUE action;action.action = HttpAction::http_get;action.queue_id = queue_id;getReply->setProperty("queue_id",queue_id);access_queue<<action;event_loop.exec();
}/// GET 其他网站获取数据 /
void Http_request::http_other_get(QString url_str,const qint32 queue_id){//设置urlrequest.setUrl(QUrl(url_str));//设置公共请求头set_request_header();//request.setRawHeader("Content-Type","*/*");//请求的数据头部//QEventLoop event_loop;QTimer::singleShot(3000, &event_loop, &QEventLoop::quit);QNetworkReply *getReply = http->get(request);ACTION_QUEUE action;action.action = HttpAction::http_other_get;action.queue_id = queue_id;getReply->setProperty("queue_id",queue_id);access_queue<<action;event_loop.exec();
}///GET 从GitHub获取地址 /
///
QJsonObject Http_request::http_get_github_data(QString url_str){//设置urlrequest.setUrl(QUrl(url_str));//设置公共请求头set_request_header();QNetworkAccessManager * http_temp = new QNetworkAccessManager();QEventLoop event_loop;QTimer::singleShot(2000, &event_loop, &QEventLoop::quit);QNetworkReply *real_reply = http_temp->get(request);event_loop.exec();if(200 == real_reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).value<int>()){QByteArray response_data = real_reply->readAll();QJsonParseError json_error;// JSON 文档为对象QJsonDocument document = QJsonDocument::fromJson(response_data, &json_error);if(document.isEmpty()){return QJsonObject();}// 转化为对象const QJsonObject data_object = document.object();return data_object;}http_temp->deleteLater(); // to avoid potential memory leakreal_reply->deleteLater(); // to avoid potential memory leakreturn QJsonObject();
} Post检测网络连通信号\获取版本\验证是否被锁
/// POST 请求获取数据 /
QJsonObject Http_request::generateErrorResponse(int code, const QString& errorMessage) {QJsonObject data_object;data_object.insert("Code",code);data_object.insert("Error",errorMessage);return data_object;
}QJsonObject Http_request::http_signal_check(QString url_str,QJsonObject data){//设置urlrequest.setUrl(QUrl(url_str));//设置公共请求头set_request_header();//转为字节流QJsonDocument json_doc;json_doc.setObject(data);QByteArray bytes_data = json_doc.toJson();QNetworkAccessManager * http_temp = new QNetworkAccessManager();QEventLoop event_loop;QTimer::singleShot(3000, &event_loop, &QEventLoop::quit);QNetworkReply *real_reply = http_temp->post(request,bytes_data);event_loop.exec();int statusCode = real_reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).value<int>();if(statusCode == 200){QByteArray response_data = real_reply->readAll();QJsonParseError json_error;// JSON 文档为对象QJsonDocument document = QJsonDocument::fromJson(response_data, &json_error);if(document.isEmpty()){return generateErrorResponse(405, "无法解析API数据");}// 转化为对象const QJsonObject data_object = document.object();return data_object;}else if(statusCode == 403){return generateErrorResponse(403, "403 Forbidden,Permission Denied请添加白名单后再试");}else {return generateErrorResponse(statusCode, QString("Unexpected error: HTTP code %1").arg(statusCode));}http_temp->deleteLater(); // to avoid potential memory leakreal_reply->deleteLater(); // to avoid potential memory leak
}/ POST请求提交数据 ///void Http_request::http_post(QString url_str,QJsonObject data){//设置urlrequest.setUrl(QUrl(url_str));//设置公共请求头set_request_header();request.setRawHeader("Authorization",token.toLocal8Bit());//转为字节流QJsonDocument json_doc;json_doc.setObject(data);QByteArray bytes_data = json_doc.toJson(QJsonDocument::Compact);QEventLoop event_loop;QTimer::singleShot(3000, &event_loop, &QEventLoop::quit);QNetworkReply *getReply = http->post(request,bytes_data);ACTION_QUEUE action;qint32 queue_id = data.value("queue_id").toInt();action.action = HttpAction::http_post;action.queue_id = queue_id;getReply->setProperty("queue_id",queue_id);access_queue<<action;event_loop.exec();
}/ POST请求提交数据 ///void Http_request::http_post_jenkins(QString url_str,QJsonObject data){//设置urlrequest.setUrl(QUrl(url_str));//设置公共请求头set_request_header();request.setRawHeader("Authorization",token.toLocal8Bit());//转为字节流QJsonDocument json_doc;json_doc.setObject(data);QByteArray bytes_data = json_doc.toJson(QJsonDocument::Compact);QEventLoop event_loop;QTimer::singleShot(3500, &event_loop, &QEventLoop::quit);QNetworkReply *getReply = http->post(request,bytes_data);ACTION_QUEUE action;qint32 queue_id = QRandomGenerator::global()->bounded(100000, 999999);action.action =HttpAction::http_post_jenkins;action.queue_id = queue_id;getReply->setProperty("queue_id",queue_id);access_queue<<action;event_loop.exec();
}/ 向其他网站发起POST请求提交数据 ///void Http_request::http_other_post(QString url_str,QJsonObject data,QMap<QString,QString>set_raw_headers){//设置urlrequest.setUrl(QUrl(url_str));//设置公共请求头set_request_header();if(!set_raw_headers.isEmpty()){foreach (QString id, set_raw_headers) {qDebug()<<"ID:"<<id<<"key:"<<set_raw_headers[id];//request.setRawHeader("Authorization",token.toLatin1());}}//转为字节流
// QJsonDocument json_doc;
// json_doc.setObject(data);
// QByteArray bytes_data = json_doc.toJson(QJsonDocument::Compact);// http_action = HttpAction::http_post_jenkins;
// QTimer::singleShot(3500, &event_loop, SLOT(quit()));
// http->post(request,bytes_data);
// event_loop.exec();
}/ PUT请求提交数据 ///void Http_request::http_put(QString url_str,QJsonObject data){//设置urlrequest.setUrl(QUrl(url_str));//设置公共请求头set_request_header();request.setRawHeader("Authorization",token.toLocal8Bit());//转为字节流QJsonDocument json_doc;json_doc.setObject(data);QByteArray bytes_data = json_doc.toJson(QJsonDocument::Compact);QEventLoop event_loop;QTimer::singleShot(3000, &event_loop, &QEventLoop::quit);QNetworkReply *getReply = http->put(request,bytes_data);ACTION_QUEUE action;qint32 queue_id = data.value("queue_id").toInt();action.action =HttpAction::http_put;action.queue_id = queue_id;getReply->setProperty("queue_id",queue_id);access_queue<<action;event_loop.exec();
}///HTTP DOWNLOAD 文件下载/
/// \brief Http_request::http_download
/// \param url_str
/// \param queue_id
///
void Http_request::http_download(QString url_str,const QString file_path, const qint32 queue_id){//设置urlrequest.setUrl(QUrl(url_str));//设置公共请求头set_request_header();request.setRawHeader("Content-Type","*/*");//请求的数据头部//QEventLoop event_loop;QTimer::singleShot(3000, &event_loop, &QEventLoop::quit);QNetworkReply *getReply = http->get(request);ACTION_QUEUE action;action.action = HttpAction::http_downalod;action.queue_id = queue_id;action.mark = file_path;getReply->setProperty("queue_id",queue_id);access_queue<<action;connect(getReply,&QNetworkReply::downloadProgress,this,[=](qint64 bytesReceived, qint64 bytesTotal){if (bytesTotal > 0) { // Add this line to check if bytesTotal is zeroemit updateProgressBar(bytesReceived,bytesTotal);}});event_loop.exec();
}///HTTP UPLOAD 文件上传 ///
/// \brief Http_request::http_upload
/// \param url
/// \param data
///
void Http_request::http_upload(QString url_str,QJsonObject data){//设置urlrequest.setUrl(QUrl(url_str));// 构造请求体QHttpMultiPart *multiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType);multiPart->setBoundary("boundaryString");//转为字节流QJsonArray file_path_list = data.value("file_list").toArray();for(int i =0;i<file_path_list.count();i++){QHttpPart filePart;QString fileName = QFileInfo(file_path_list.at(i).toString()).fileName();filePart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"files\"; filename=\"" + fileName + "\""));QFile *file = new QFile(file_path_list.at(i).toString());if (!file->open(QIODevice::ReadOnly)) {qWarning() << "Cannot open file:" << file_path_list.at(i).toString();delete file;continue;}filePart.setBodyDevice(file);file->setParent(multiPart); // We cannot delete the file now, so set it to be the child of multiPartmultiPart->append(filePart);}//去除file列表数据 添加JSON数据data.remove("file_list");QJsonDocument json_doc;json_doc.setObject(data);QByteArray bytes_data = json_doc.toJson(QJsonDocument::Compact);QHttpPart jsonPart;jsonPart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("application/json;name=\"json_data\""));jsonPart.setBody(bytes_data);multiPart->append(jsonPart);//设置公共请求头request.setRawHeader("Authorization",token.toLocal8Bit());request.setRawHeader("Content-Type", "multipart/form-data; boundary=" + multiPart->boundary());//设置访问超时QTimer *timeoutTimer = new QTimer(this);timeoutTimer->setSingleShot(true);QNetworkReply *getReply = http->post(request,multiPart);ACTION_QUEUE action;qint32 queue_id = data.value("queue_id").toInt();action.action =HttpAction::http_upload;action.queue_id = queue_id;getReply->setProperty("queue_id",queue_id);access_queue<<action;connect(getReply, &QNetworkReply::uploadProgress, this, [=](qint64 bytesSent, qint64 bytesTotal){if (bytesTotal > 0) { // Add this line to check if bytesTotal is zeroemit updateProgressBar(bytesSent,bytesTotal);}});connect(timeoutTimer, &QTimer::timeout, getReply, &QNetworkReply::abort);timeoutTimer->start(3000);multiPart->setParent(getReply); // we cannot delete the multiPart now, so delete it with the reply
}