This commit is contained in:
zhuzichu 2023-09-04 18:37:55 +08:00
parent ba32c92133
commit f7b7d30a6f
9 changed files with 447 additions and 397 deletions

View File

@ -10,14 +10,57 @@ import "qrc:///example/qml/component"
FluContentPage{ FluContentPage{
title:"Http" title:"Http"
property string cacheDirPath: FluTools.getApplicationDirPath() + "/cache/http"
FluHttp{ FluHttp{
id:http id:http
} }
FluHttp{
id:http_cache_ifnonecacherequest
cacheMode:FluHttpType.IfNoneCacheRequest
cacheDir:cacheDirPath
}
FluHttp{
id:http_cache_requestfailedreadcache
cacheMode:FluHttpType.RequestFailedReadCache
cacheDir:cacheDirPath
}
FluHttp{
id:http_cache_firstcachethenrequest
cacheMode:FluHttpType.FirstCacheThenRequest
cacheDir:cacheDirPath
}
HttpCallable{
id:callable
onStart: {
showLoading()
}
onFinish: {
hideLoading()
}
onError:
(status,errorString,result)=>{
console.debug(status+";"+errorString+";"+result)
}
onSuccess:
(result)=>{
text_info.text = result
console.debug(result)
}
onCache:
(result)=>{
text_info.text = result
console.debug(result)
}
}
Flickable{ Flickable{
id:layout_flick id:layout_flick
width: 160 width: 200
clip: true clip: true
anchors{ anchors{
top: parent.top top: parent.top
@ -36,24 +79,6 @@ FluContentPage{
implicitHeight: 36 implicitHeight: 36
text: "Get请求" text: "Get请求"
onClicked: { onClicked: {
var callable = {}
callable.onStart = function(){
showLoading()
}
callable.onFinish = function(){
hideLoading()
}
callable.onSuccess = function(result){
text_info.text = result
console.debug(result)
}
callable.onCache = function(result){
text_info.text = result
console.debug(result)
}
callable.onError = function(status,errorString){
console.debug(status+";"+errorString)
}
http.get("https://httpbingo.org/get",callable) http.get("https://httpbingo.org/get",callable)
} }
} }
@ -62,24 +87,6 @@ FluContentPage{
implicitHeight: 36 implicitHeight: 36
text: "Post表单请求" text: "Post表单请求"
onClicked: { onClicked: {
var callable = {}
callable.onStart = function(){
showLoading()
}
callable.onFinish = function(){
hideLoading()
}
callable.onSuccess = function(result){
text_info.text = result
console.debug(result)
}
callable.onCache = function(result){
text_info.text = result
console.debug(result)
}
callable.onError = function(status,errorString){
console.debug(status+";"+errorString)
}
var param = {} var param = {}
param.custname = "朱子楚" param.custname = "朱子楚"
param.custtel = "1234567890" param.custtel = "1234567890"
@ -92,24 +99,6 @@ FluContentPage{
implicitHeight: 36 implicitHeight: 36
text: "Post Json请求" text: "Post Json请求"
onClicked: { onClicked: {
var callable = {}
callable.onStart = function(){
showLoading()
}
callable.onFinish = function(){
hideLoading()
}
callable.onSuccess = function(result){
text_info.text = result
console.debug(result)
}
callable.onCache = function(result){
text_info.text = result
console.debug(result)
}
callable.onError = function(status,errorString){
console.debug(status+";"+errorString)
}
var param = {} var param = {}
param.custname = "朱子楚" param.custname = "朱子楚"
param.custtel = "1234567890" param.custtel = "1234567890"
@ -122,24 +111,6 @@ FluContentPage{
implicitHeight: 36 implicitHeight: 36
text: "Post String请求" text: "Post String请求"
onClicked: { onClicked: {
var callable = {}
callable.onStart = function(){
showLoading()
}
callable.onFinish = function(){
hideLoading()
}
callable.onSuccess = function(result){
text_info.text = result
console.debug(result)
}
callable.onCache = function(result){
text_info.text = result
console.debug(result)
}
callable.onError = function(status,errorString){
console.debug(status+";"+errorString)
}
var param = "我命由我不由天" var param = "我命由我不由天"
http.postString("https://httpbingo.org/post",callable,param) http.postString("https://httpbingo.org/post",callable,param)
} }
@ -162,9 +133,86 @@ FluContentPage{
file_dialog.open() file_dialog.open()
} }
} }
FluButton{
implicitWidth: parent.width
implicitHeight: 36
text: "FirstCacheThenRequest缓存"
onClicked: {
var param = {}
param.cacheMode = "FirstCacheThenRequest"
http_cache_firstcachethenrequest.post("https://httpbingo.org/post",callable,param)
}
}
FluButton{
implicitWidth: parent.width
implicitHeight: 36
text: "RequestFailedReadCache缓存"
onClicked: {
var param = {}
param.cacheMode = "RequestFailedReadCache"
http_cache_requestfailedreadcache.post("https://httpbingo.org/post",callable,param)
}
}
FluButton{
implicitWidth: parent.width
implicitHeight: 36
text: "IfNoneCacheRequest缓存"
onClicked: {
var param = {}
param.cacheMode = "IfNoneCacheRequest"
http_cache_ifnonecacherequest.post("https://httpbingo.org/post",callable,param)
}
}
FluButton{
implicitWidth: parent.width
implicitHeight: 36
text: "删除缓存"
onClicked: {
console.debug(FluTools.removeDir(cacheDirPath))
}
}
FluButton{
implicitWidth: parent.width
implicitHeight: 36
text: "清空右边数据"
onClicked: {
text_info.text = ""
}
}
} }
} }
HttpCallable{
id:callable_upload
onStart: {
btn_upload.disabled = true
}
onFinish: {
btn_upload.disabled = false
btn_upload.text = "上传文件"
layout_upload_file_size.visible = false
text_upload_file_size.text = ""
}
onError:
(status,errorString,result)=>{
text_info.text = result
console.debug(result)
}
onSuccess:
(result)=>{
text_info.text = result
}
onUploadProgress:
(sent,total)=>{
var locale = Qt.locale()
var precent = (sent/total * 100).toFixed(0) + "%"
btn_upload.text = "上传中..."+precent
text_upload_file_size.text = "%1/%2".arg(locale.formattedDataSize(sent)).arg(locale.formattedDataSize(total))
layout_upload_file_size.visible = true
}
}
FileDialog { FileDialog {
id: file_dialog id: file_dialog
onAccepted: { onAccepted: {
@ -175,65 +223,46 @@ FluContentPage{
var filePath = FluTools.toLocalPath(fileUrl) var filePath = FluTools.toLocalPath(fileUrl)
param[fileName] = filePath param[fileName] = filePath
} }
console.debug(JSON.stringify(param)) http.upload("https://httpbingo.org/post",callable_upload,param)
var callable = {}
callable.onStart = function(){
btn_upload.disabled = true
}
callable.onFinish = function(){
btn_upload.disabled = false
btn_upload.text = "上传文件"
layout_upload_file_size.visible = false
text_upload_file_size.text = ""
}
callable.onSuccess = function(result){
text_info.text = result
console.debug(result)
}
callable.onError = function(status,errorString,result){
text_info.text = result
console.debug(result)
}
callable.onUploadProgress = function(sent,total){
var locale = Qt.locale()
var precent = (sent/total * 100).toFixed(0) + "%"
btn_upload.text = "上传中..."+precent
text_upload_file_size.text = "%1/%2".arg(locale.formattedDataSize(sent)).arg(locale.formattedDataSize(total))
layout_upload_file_size.visible = true
}
http.upload("https://httpbingo.org/post",callable,param)
} }
} }
FolderDialog { HttpCallable{
id: folder_dialog id:callable_download
currentFolder: StandardPaths.standardLocations(StandardPaths.DownloadLocation)[0] onStart: {
onAccepted: { btn_download.disabled = true
var callable = {} }
callable.onStart = function(){ onFinish: {
btn_download.disabled = true btn_download.disabled = false
btn_download.text = "下载文件"
layout_download_file_size.visible = false
text_download_file_size.text = ""
}
onError:
(status,errorString,result)=>{
showError(errorString)
console.debug(status+";"+errorString+";"+result)
} }
callable.onFinish = function(){ onSuccess:
btn_download.disabled = false (result)=>{
btn_download.text = "下载文件"
layout_download_file_size.visible = false
text_download_file_size.text = ""
}
callable.onSuccess = function(result){
showSuccess(result) showSuccess(result)
} }
callable.onError = function(status,errorString){ onDownloadProgress:
showError(errorString) (recv,total)=>{
}
callable.onDownloadProgress = function(recv,total){
var locale = Qt.locale() var locale = Qt.locale()
var precent = (recv/total * 100).toFixed(0) + "%" var precent = (recv/total * 100).toFixed(0) + "%"
btn_download.text = "下载中..."+precent btn_download.text = "下载中..."+precent
text_download_file_size.text = "%1/%2".arg(locale.formattedDataSize(recv)).arg(locale.formattedDataSize(total)) text_download_file_size.text = "%1/%2".arg(locale.formattedDataSize(recv)).arg(locale.formattedDataSize(total))
layout_download_file_size.visible = true layout_download_file_size.visible = true
} }
}
FolderDialog {
id: folder_dialog
currentFolder: StandardPaths.standardLocations(StandardPaths.DownloadLocation)[0]
onAccepted: {
var path = FluTools.toLocalPath(currentFolder)+ "/big_buck_bunny.mp4" var path = FluTools.toLocalPath(currentFolder)+ "/big_buck_bunny.mp4"
http.download("http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4",callable,path) http.download("http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4",callable_download,path)
} }
} }
@ -277,7 +306,6 @@ FluContentPage{
} }
} }
FluRectangle{ FluRectangle{
id:layout_upload_file_size id:layout_upload_file_size
radius: [4,4,4,4] radius: [4,4,4,4]

View File

@ -309,27 +309,33 @@ CustomWindow {
} }
} }
function checkUpdate(){
var callable = {} HttpCallable{
callable.onStart = function(){ id:callable
onStart: {
console.debug("satrt check update...") console.debug("satrt check update...")
} }
callable.onFinish = function(){ onFinish: {
console.debug("check update finish") console.debug("check update finish")
} }
callable.onSuccess = function(result){ onSuccess:
var data = JSON.parse(result) (result)=>{
console.debug("current version "+appInfo.version) var data = JSON.parse(result)
console.debug("new version "+data.tag_name) console.debug("current version "+appInfo.version)
if(data.tag_name !== appInfo.version){ console.debug("new version "+data.tag_name)
dialog_update.newVerson = data.tag_name if(data.tag_name !== appInfo.version){
dialog_update.body = data.body dialog_update.newVerson = data.tag_name
dialog_update.open() dialog_update.body = data.body
dialog_update.open()
}
} }
} onError:
callable.onError = function(status,errorString){ (status,errorString)=>{
console.debug(status+";"+errorString) console.debug(status+";"+errorString)
} }
}
function checkUpdate(){
http.get("https://api.github.com/repos/zhuzichu520/FluentUI/releases/latest",callable) http.get("https://api.github.com/repos/zhuzichu520/FluentUI/releases/latest",callable)
} }

View File

@ -11,14 +11,57 @@ import "../component"
FluContentPage{ FluContentPage{
title:"Http" title:"Http"
property string cacheDirPath: FluTools.getApplicationDirPath() + "/cache/http"
FluHttp{ FluHttp{
id:http id:http
} }
FluHttp{
id:http_cache_ifnonecacherequest
cacheMode:FluHttpType.IfNoneCacheRequest
cacheDir:cacheDirPath
}
FluHttp{
id:http_cache_requestfailedreadcache
cacheMode:FluHttpType.RequestFailedReadCache
cacheDir:cacheDirPath
}
FluHttp{
id:http_cache_firstcachethenrequest
cacheMode:FluHttpType.FirstCacheThenRequest
cacheDir:cacheDirPath
}
HttpCallable{
id:callable
onStart: {
showLoading()
}
onFinish: {
hideLoading()
}
onError:
(status,errorString,result)=>{
console.debug(status+";"+errorString+";"+result)
}
onSuccess:
(result)=>{
text_info.text = result
console.debug(result)
}
onCache:
(result)=>{
text_info.text = result
console.debug(result)
}
}
Flickable{ Flickable{
id:layout_flick id:layout_flick
width: 160 width: 200
clip: true clip: true
anchors{ anchors{
top: parent.top top: parent.top
@ -37,20 +80,6 @@ FluContentPage{
implicitHeight: 36 implicitHeight: 36
text: "Get请求" text: "Get请求"
onClicked: { onClicked: {
var callable = {}
callable.onStart = function(){
showLoading()
}
callable.onFinish = function(){
hideLoading()
}
callable.onSuccess = function(result){
text_info.text = result
console.debug(result)
}
callable.onError = function(status,errorString){
console.debug(status+";"+errorString)
}
http.get("https://httpbingo.org/get",callable) http.get("https://httpbingo.org/get",callable)
} }
} }
@ -59,20 +88,6 @@ FluContentPage{
implicitHeight: 36 implicitHeight: 36
text: "Post表单请求" text: "Post表单请求"
onClicked: { onClicked: {
var callable = {}
callable.onStart = function(){
showLoading()
}
callable.onFinish = function(){
hideLoading()
}
callable.onSuccess = function(result){
text_info.text = result
console.debug(result)
}
callable.onError = function(status,errorString){
console.debug(status+";"+errorString)
}
var param = {} var param = {}
param.custname = "朱子楚" param.custname = "朱子楚"
param.custtel = "1234567890" param.custtel = "1234567890"
@ -85,20 +100,6 @@ FluContentPage{
implicitHeight: 36 implicitHeight: 36
text: "Post Json请求" text: "Post Json请求"
onClicked: { onClicked: {
var callable = {}
callable.onStart = function(){
showLoading()
}
callable.onFinish = function(){
hideLoading()
}
callable.onSuccess = function(result){
text_info.text = result
console.debug(result)
}
callable.onError = function(status,errorString){
console.debug(status+";"+errorString)
}
var param = {} var param = {}
param.custname = "朱子楚" param.custname = "朱子楚"
param.custtel = "1234567890" param.custtel = "1234567890"
@ -111,20 +112,6 @@ FluContentPage{
implicitHeight: 36 implicitHeight: 36
text: "Post String请求" text: "Post String请求"
onClicked: { onClicked: {
var callable = {}
callable.onStart = function(){
showLoading()
}
callable.onFinish = function(){
hideLoading()
}
callable.onSuccess = function(result){
text_info.text = result
console.debug(result)
}
callable.onError = function(status,errorString){
console.debug(status+";"+errorString)
}
var param = "我命由我不由天" var param = "我命由我不由天"
http.postString("https://httpbingo.org/post",callable,param) http.postString("https://httpbingo.org/post",callable,param)
} }
@ -147,9 +134,86 @@ FluContentPage{
file_dialog.open() file_dialog.open()
} }
} }
FluButton{
implicitWidth: parent.width
implicitHeight: 36
text: "FirstCacheThenRequest缓存"
onClicked: {
var param = {}
param.cacheMode = "FirstCacheThenRequest"
http_cache_firstcachethenrequest.post("https://httpbingo.org/post",callable,param)
}
}
FluButton{
implicitWidth: parent.width
implicitHeight: 36
text: "RequestFailedReadCache缓存"
onClicked: {
var param = {}
param.cacheMode = "RequestFailedReadCache"
http_cache_requestfailedreadcache.post("https://httpbingo.org/post",callable,param)
}
}
FluButton{
implicitWidth: parent.width
implicitHeight: 36
text: "IfNoneCacheRequest缓存"
onClicked: {
var param = {}
param.cacheMode = "IfNoneCacheRequest"
http_cache_ifnonecacherequest.post("https://httpbingo.org/post",callable,param)
}
}
FluButton{
implicitWidth: parent.width
implicitHeight: 36
text: "删除缓存"
onClicked: {
console.debug(FluTools.removeDir(cacheDirPath))
}
}
FluButton{
implicitWidth: parent.width
implicitHeight: 36
text: "清空右边数据"
onClicked: {
text_info.text = ""
}
}
} }
} }
HttpCallable{
id:callable_upload
onStart: {
btn_upload.disabled = true
}
onFinish: {
btn_upload.disabled = false
btn_upload.text = "上传文件"
layout_upload_file_size.visible = false
text_upload_file_size.text = ""
}
onError:
(status,errorString,result)=>{
text_info.text = result
console.debug(result)
}
onSuccess:
(result)=>{
text_info.text = result
}
onUploadProgress:
(sent,total)=>{
var locale = Qt.locale()
var precent = (sent/total * 100).toFixed(0) + "%"
btn_upload.text = "上传中..."+precent
text_upload_file_size.text = "%1/%2".arg(locale.formattedDataSize(sent)).arg(locale.formattedDataSize(total))
layout_upload_file_size.visible = true
}
}
FileDialog { FileDialog {
id: file_dialog id: file_dialog
onAccepted: { onAccepted: {
@ -160,65 +224,46 @@ FluContentPage{
var filePath = FluTools.toLocalPath(fileUrl) var filePath = FluTools.toLocalPath(fileUrl)
param[fileName] = filePath param[fileName] = filePath
} }
console.debug(JSON.stringify(param)) http.upload("https://httpbingo.org/post",callable_upload,param)
var callable = {}
callable.onStart = function(){
btn_upload.disabled = true
}
callable.onFinish = function(){
btn_upload.disabled = false
btn_upload.text = "上传文件"
layout_upload_file_size.visible = false
text_upload_file_size.text = ""
}
callable.onSuccess = function(result){
text_info.text = result
console.debug(result)
}
callable.onError = function(status,errorString,result){
text_info.text = result
console.debug(result)
}
callable.onUploadProgress = function(sent,total){
var locale = Qt.locale()
var precent = (sent/total * 100).toFixed(0) + "%"
btn_upload.text = "上传中..."+precent
text_upload_file_size.text = "%1/%2".arg(locale.formattedDataSize(sent)).arg(locale.formattedDataSize(total))
layout_upload_file_size.visible = true
}
http.upload("https://httpbingo.org/post",callable,param)
} }
} }
FolderDialog { HttpCallable{
id: folder_dialog id:callable_download
currentFolder: StandardPaths.standardLocations(StandardPaths.DownloadLocation)[0] onStart: {
onAccepted: { btn_download.disabled = true
var callable = {} }
callable.onStart = function(){ onFinish: {
btn_download.disabled = true btn_download.disabled = false
btn_download.text = "下载文件"
layout_download_file_size.visible = false
text_download_file_size.text = ""
}
onError:
(status,errorString,result)=>{
showError(errorString)
console.debug(status+";"+errorString+";"+result)
} }
callable.onFinish = function(){ onSuccess:
btn_download.disabled = false (result)=>{
btn_download.text = "下载文件"
layout_download_file_size.visible = false
text_download_file_size.text = ""
}
callable.onSuccess = function(result){
showSuccess(result) showSuccess(result)
} }
callable.onError = function(status,errorString){ onDownloadProgress:
showError(errorString) (recv,total)=>{
}
callable.onDownloadProgress = function(recv,total){
var locale = Qt.locale() var locale = Qt.locale()
var precent = (recv/total * 100).toFixed(0) + "%" var precent = (recv/total * 100).toFixed(0) + "%"
btn_download.text = "下载中..."+precent btn_download.text = "下载中..."+precent
text_download_file_size.text = "%1/%2".arg(locale.formattedDataSize(recv)).arg(locale.formattedDataSize(total)) text_download_file_size.text = "%1/%2".arg(locale.formattedDataSize(recv)).arg(locale.formattedDataSize(total))
layout_download_file_size.visible = true layout_download_file_size.visible = true
} }
}
FolderDialog {
id: folder_dialog
currentFolder: StandardPaths.standardLocations(StandardPaths.DownloadLocation)[0]
onAccepted: {
var path = FluTools.toLocalPath(currentFolder)+ "/big_buck_bunny.mp4" var path = FluTools.toLocalPath(currentFolder)+ "/big_buck_bunny.mp4"
http.download("http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4",callable,path) http.download("http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4",callable_download,path)
} }
} }
@ -262,7 +307,6 @@ FluContentPage{
} }
} }
FluRectangle{ FluRectangle{
id:layout_upload_file_size id:layout_upload_file_size
radius: [4,4,4,4] radius: [4,4,4,4]

View File

@ -310,27 +310,32 @@ CustomWindow {
} }
} }
function checkUpdate(){ HttpCallable{
var callable = {} id:callable
callable.onStart = function(){ onStart: {
console.debug("satrt check update...") console.debug("satrt check update...")
} }
callable.onFinish = function(){ onFinish: {
console.debug("check update finish") console.debug("check update finish")
} }
callable.onSuccess = function(result){ onSuccess:
var data = JSON.parse(result) (result)=>{
console.debug("current version "+appInfo.version) var data = JSON.parse(result)
console.debug("new version "+data.tag_name) console.debug("current version "+appInfo.version)
if(data.tag_name !== appInfo.version){ console.debug("new version "+data.tag_name)
dialog_update.newVerson = data.tag_name if(data.tag_name !== appInfo.version){
dialog_update.body = data.body dialog_update.newVerson = data.tag_name
dialog_update.open() dialog_update.body = data.body
dialog_update.open()
}
} }
} onError:
callable.onError = function(status,errorString){ (status,errorString)=>{
console.debug(status+";"+errorString) console.debug(status+";"+errorString)
} }
}
function checkUpdate(){
http.get("https://api.github.com/repos/zhuzichu520/FluentUI/releases/latest",callable) http.get("https://api.github.com/repos/zhuzichu520/FluentUI/releases/latest",callable)
} }

View File

@ -14,6 +14,11 @@
#include "FluApp.h" #include "FluApp.h"
#include "FluTools.h" #include "FluTools.h"
HttpCallable::HttpCallable(QObject *parent)
: QObject{parent}
{
}
FluHttp::FluHttp(QObject *parent) FluHttp::FluHttp(QObject *parent)
: QObject{parent} : QObject{parent}
{ {
@ -39,18 +44,18 @@ void FluHttp::handleReply(QNetworkReply* reply){
_cacheReply.append(reply); _cacheReply.append(reply);
} }
void FluHttp::post(QString url,QJSValue callable,QMap<QString, QVariant> params,QMap<QString, QVariant> headers){ void FluHttp::post(QString url,HttpCallable* callable,QMap<QString, QVariant> params,QMap<QString, QVariant> headers){
auto requestMap = toRequest(url,params,headers,"post");
QMap<QString, QVariant> data = invokeIntercept(requestMap).toMap();
QThreadPool::globalInstance()->start([=](){ QThreadPool::globalInstance()->start([=](){
onStart(callable); auto requestMap = toRequest(url,params,headers,"post");
QMap<QString, QVariant> data = invokeIntercept(requestMap).toMap();
Q_EMIT callable->start();
if(_cacheMode == FluHttpType::CacheMode::IfNoneCacheRequest && cacheExists(requestMap)){ if(_cacheMode == FluHttpType::CacheMode::IfNoneCacheRequest && cacheExists(requestMap)){
onCache(callable,readCache(requestMap)); Q_EMIT callable->cache(readCache(requestMap));
onFinish(callable); Q_EMIT callable->finish();
return; return;
} }
if(_cacheMode == FluHttpType::CacheMode::FirstCacheThenRequest){ if(_cacheMode == FluHttpType::CacheMode::FirstCacheThenRequest){
onCache(callable,readCache(requestMap)); Q_EMIT callable->cache(readCache(requestMap));
} }
for (int i = 0; i < retry(); ++i) { for (int i = 0; i < retry(); ++i) {
QNetworkAccessManager manager; QNetworkAccessManager manager;
@ -85,33 +90,34 @@ void FluHttp::post(QString url,QJSValue callable,QMap<QString, QVariant> params,
reply = nullptr; reply = nullptr;
if (isSuccess) { if (isSuccess) {
handleCache(requestMap,result); handleCache(requestMap,result);
onSuccess(callable,result); Q_EMIT callable->success(result);
break; break;
}else{ }else{
if(i == retry()-1){ if(i == retry()-1){
if(_cacheMode == FluHttpType::CacheMode::RequestFailedReadCache){ if(_cacheMode == FluHttpType::CacheMode::RequestFailedReadCache){
onCache(callable,readCache(requestMap)); Q_EMIT callable->cache(readCache(requestMap));
} }
onError(callable,status,errorString,result); Q_EMIT callable->error(status,errorString,result);
} }
} }
} }
onFinish(callable); Q_EMIT callable->finish();
// Q_EMIT callable->finish();
}); });
} }
void FluHttp::postString(QString url,QJSValue callable,QString params,QMap<QString, QVariant> headers){ void FluHttp::postString(QString url,HttpCallable* callable,QString params,QMap<QString, QVariant> headers){
auto requestMap = toRequest(url,params,headers,"postString");
QMap<QString, QVariant> data = invokeIntercept(requestMap).toMap();
QThreadPool::globalInstance()->start([=](){ QThreadPool::globalInstance()->start([=](){
onStart(callable); auto requestMap = toRequest(url,params,headers,"postString");
QMap<QString, QVariant> data = invokeIntercept(requestMap).toMap();
Q_EMIT callable->start();
if(_cacheMode == FluHttpType::CacheMode::IfNoneCacheRequest && cacheExists(requestMap)){ if(_cacheMode == FluHttpType::CacheMode::IfNoneCacheRequest && cacheExists(requestMap)){
onCache(callable,readCache(requestMap)); Q_EMIT callable->cache(readCache(requestMap));
onFinish(callable); Q_EMIT callable->finish();
return; return;
} }
if(_cacheMode == FluHttpType::CacheMode::FirstCacheThenRequest){ if(_cacheMode == FluHttpType::CacheMode::FirstCacheThenRequest){
onCache(callable,readCache(requestMap)); Q_EMIT callable->cache(readCache(requestMap));
} }
for (int i = 0; i < retry(); ++i) { for (int i = 0; i < retry(); ++i) {
QNetworkAccessManager manager; QNetworkAccessManager manager;
@ -137,33 +143,33 @@ void FluHttp::postString(QString url,QJSValue callable,QString params,QMap<QStri
reply = nullptr; reply = nullptr;
if (isSuccess) { if (isSuccess) {
handleCache(requestMap,result); handleCache(requestMap,result);
onSuccess(callable,result); Q_EMIT callable->success(result);
break; break;
}else{ }else{
if(i == retry()-1){ if(i == retry()-1){
if(_cacheMode == FluHttpType::CacheMode::RequestFailedReadCache){ if(_cacheMode == FluHttpType::CacheMode::RequestFailedReadCache){
onCache(callable,readCache(requestMap)); Q_EMIT callable->cache(readCache(requestMap));
} }
onError(callable,status,errorString,result); Q_EMIT callable->error(status,errorString,result);
} }
} }
} }
onFinish(callable); Q_EMIT callable->finish();
}); });
} }
void FluHttp::postJson(QString url,QJSValue callable,QMap<QString, QVariant> params,QMap<QString, QVariant> headers){ void FluHttp::postJson(QString url,HttpCallable* callable,QMap<QString, QVariant> params,QMap<QString, QVariant> headers){
auto requestMap = toRequest(url,params,headers,"postJson");
QMap<QString, QVariant> data = invokeIntercept(requestMap).toMap();
QThreadPool::globalInstance()->start([=](){ QThreadPool::globalInstance()->start([=](){
onStart(callable); auto requestMap = toRequest(url,params,headers,"postJson");
QMap<QString, QVariant> data = invokeIntercept(requestMap).toMap();
Q_EMIT callable->start();
if(_cacheMode == FluHttpType::CacheMode::IfNoneCacheRequest && cacheExists(requestMap)){ if(_cacheMode == FluHttpType::CacheMode::IfNoneCacheRequest && cacheExists(requestMap)){
onCache(callable,readCache(requestMap)); Q_EMIT callable->cache(readCache(requestMap));
onFinish(callable); Q_EMIT callable->finish();
return; return;
} }
if(_cacheMode == FluHttpType::CacheMode::FirstCacheThenRequest){ if(_cacheMode == FluHttpType::CacheMode::FirstCacheThenRequest){
onCache(callable,readCache(requestMap)); Q_EMIT callable->cache(readCache(requestMap));
} }
for (int i = 0; i < retry(); ++i) { for (int i = 0; i < retry(); ++i) {
QNetworkAccessManager manager; QNetworkAccessManager manager;
@ -189,32 +195,32 @@ void FluHttp::postJson(QString url,QJSValue callable,QMap<QString, QVariant> par
reply = nullptr; reply = nullptr;
if (isSuccess) { if (isSuccess) {
handleCache(requestMap,result); handleCache(requestMap,result);
onSuccess(callable,result); Q_EMIT callable->success(result);
break; break;
}else{ }else{
if(i == retry()-1){ if(i == retry()-1){
if(_cacheMode == FluHttpType::CacheMode::RequestFailedReadCache){ if(_cacheMode == FluHttpType::CacheMode::RequestFailedReadCache){
onCache(callable,readCache(requestMap)); Q_EMIT callable->cache(readCache(requestMap));
} }
onError(callable,status,errorString,result); Q_EMIT callable->error(status,errorString,result);
} }
} }
} }
onFinish(callable); Q_EMIT callable->finish();
}); });
} }
void FluHttp::get(QString url,QJSValue callable,QMap<QString, QVariant> params,QMap<QString, QVariant> headers){ void FluHttp::get(QString url,HttpCallable* callable,QMap<QString, QVariant> params,QMap<QString, QVariant> headers){
auto requestMap = toRequest(url,params,headers,"get");
QMap<QString, QVariant> data = invokeIntercept(requestMap).toMap();
QThreadPool::globalInstance()->start([=](){ QThreadPool::globalInstance()->start([=](){
onStart(callable); auto requestMap = toRequest(url,params,headers,"get");
QMap<QString, QVariant> data = invokeIntercept(requestMap).toMap();
Q_EMIT callable->start();
if(_cacheMode == FluHttpType::CacheMode::FirstCacheThenRequest){ if(_cacheMode == FluHttpType::CacheMode::FirstCacheThenRequest){
onCache(callable,readCache(requestMap)); Q_EMIT callable->cache(readCache(requestMap));
} }
if(_cacheMode == FluHttpType::CacheMode::IfNoneCacheRequest && cacheExists(requestMap)){ if(_cacheMode == FluHttpType::CacheMode::IfNoneCacheRequest && cacheExists(requestMap)){
onCache(callable,readCache(requestMap)); Q_EMIT callable->cache(readCache(requestMap));
onFinish(callable); Q_EMIT callable->finish();
return; return;
} }
for (int i = 0; i < retry(); ++i) { for (int i = 0; i < retry(); ++i) {
@ -240,26 +246,26 @@ void FluHttp::get(QString url,QJSValue callable,QMap<QString, QVariant> params,Q
reply = nullptr; reply = nullptr;
if (isSuccess) { if (isSuccess) {
handleCache(requestMap,result); handleCache(requestMap,result);
onSuccess(callable,result); Q_EMIT callable->success(result);
break; break;
}else{ }else{
if(i == retry()-1){ if(i == retry()-1){
if(_cacheMode == FluHttpType::CacheMode::RequestFailedReadCache){ if(_cacheMode == FluHttpType::CacheMode::RequestFailedReadCache){
onCache(callable,readCache(requestMap)); Q_EMIT callable->cache(readCache(requestMap));
} }
onError(callable,status,errorString,result); Q_EMIT callable->error(status,errorString,result);
} }
} }
} }
onFinish(callable); Q_EMIT callable->finish();
}); });
} }
void FluHttp::download(QString url,QJSValue callable,QString filePath,QMap<QString, QVariant> params,QMap<QString, QVariant> headers){ void FluHttp::download(QString url,HttpCallable* callable,QString filePath,QMap<QString, QVariant> params,QMap<QString, QVariant> headers){
auto requestMap = toRequest(url,params,headers,"download");
QMap<QString, QVariant> data = invokeIntercept(requestMap).toMap();
QThreadPool::globalInstance()->start([=](){ QThreadPool::globalInstance()->start([=](){
onStart(callable); auto requestMap = toRequest(url,params,headers,"download");
QMap<QString, QVariant> data = invokeIntercept(requestMap).toMap();
Q_EMIT callable->start();
QNetworkAccessManager manager; QNetworkAccessManager manager;
QUrl _url(url); QUrl _url(url);
addQueryParam(&_url,data["params"].toMap()); addQueryParam(&_url,data["params"].toMap());
@ -269,8 +275,8 @@ void FluHttp::download(QString url,QJSValue callable,QString filePath,QMap<QStri
QIODevice::OpenMode mode = QIODevice::WriteOnly|QIODevice::Truncate; QIODevice::OpenMode mode = QIODevice::WriteOnly|QIODevice::Truncate;
if (!file->open(mode)) if (!file->open(mode))
{ {
onError(callable,-1,QString("Url: %1 %2 Non-Writable").arg(request.url().toString(),file->fileName()),""); Q_EMIT callable->error(-1,QString("Url: %1 %2 Non-Writable").arg(request.url().toString(),file->fileName()),"");
onFinish(callable); Q_EMIT callable->finish();
return; return;
} }
QEventLoop loop; QEventLoop loop;
@ -280,27 +286,27 @@ void FluHttp::download(QString url,QJSValue callable,QString filePath,QMap<QStri
QPointer<QNetworkReply> reply = manager.get(request); QPointer<QNetworkReply> reply = manager.get(request);
_cacheReply.append(reply); _cacheReply.append(reply);
connect(reply,&QNetworkReply::downloadProgress,this,[=](qint64 bytesReceived, qint64 bytesTotal){ connect(reply,&QNetworkReply::downloadProgress,this,[=](qint64 bytesReceived, qint64 bytesTotal){
onDownloadProgress(callable,bytesReceived,bytesTotal); Q_EMIT callable->downloadProgress(bytesReceived,bytesTotal);
}); });
loop.exec(); loop.exec();
if (reply->error() == QNetworkReply::NoError) { if (reply->error() == QNetworkReply::NoError) {
file->write(reply->readAll()); file->write(reply->readAll());
onSuccess(callable,filePath); Q_EMIT callable->success(filePath);
}else{ }else{
onError(callable,reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(),reply->errorString(),""); Q_EMIT callable->error(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(),reply->errorString(),"");
} }
_cacheReply.removeOne(reply); _cacheReply.removeOne(reply);
reply->deleteLater(); reply->deleteLater();
reply = nullptr; reply = nullptr;
onFinish(callable); Q_EMIT callable->finish();
}); });
} }
void FluHttp::upload(QString url,QJSValue callable,QMap<QString, QVariant> params,QMap<QString, QVariant> headers){ void FluHttp::upload(QString url,HttpCallable* callable,QMap<QString, QVariant> params,QMap<QString, QVariant> headers){
auto requestMap = toRequest(url,params,headers,"upload");
QMap<QString, QVariant> data = invokeIntercept(requestMap).toMap();
QThreadPool::globalInstance()->start([=](){ QThreadPool::globalInstance()->start([=](){
onStart(callable); auto requestMap = toRequest(url,params,headers,"upload");
QMap<QString, QVariant> data = invokeIntercept(requestMap).toMap();
Q_EMIT callable->start();
QNetworkAccessManager manager; QNetworkAccessManager manager;
manager.setTransferTimeout(timeout()); manager.setTransferTimeout(timeout());
QUrl _url(url); QUrl _url(url);
@ -328,7 +334,7 @@ void FluHttp::upload(QString url,QJSValue callable,QMap<QString, QVariant> param
loop.quit(); loop.quit();
}); });
connect(reply,&QNetworkReply::uploadProgress,this,[=](qint64 bytesSent, qint64 bytesTotal){ connect(reply,&QNetworkReply::uploadProgress,this,[=](qint64 bytesSent, qint64 bytesTotal){
onUploadProgress(callable,bytesSent,bytesTotal); Q_EMIT callable->uploadProgress(bytesSent,bytesTotal);
}); });
loop.exec(); loop.exec();
QString result = QString::fromUtf8(reply->readAll()); QString result = QString::fromUtf8(reply->readAll());
@ -339,11 +345,11 @@ void FluHttp::upload(QString url,QJSValue callable,QMap<QString, QVariant> param
reply->deleteLater(); reply->deleteLater();
reply = nullptr; reply = nullptr;
if (isSuccess) { if (isSuccess) {
onSuccess(callable,result); Q_EMIT callable->success(result);
}else{ }else{
onError(callable,status,errorString,result); Q_EMIT callable->error(status,errorString,result);
} }
onFinish(callable); Q_EMIT callable->finish();
}); });
} }
@ -362,7 +368,7 @@ QVariant FluHttp::invokeIntercept(QMap<QString, QVariant> request){
return request; return request;
} }
QVariant target; QVariant target;
QMetaObject::invokeMethod(FluApp::getInstance()->httpInterceptor(), "onIntercept",Q_RETURN_ARG(QVariant,target),Q_ARG(QVariant, request)); QMetaObject::invokeMethod(FluApp::getInstance()->httpInterceptor(), "onIntercept",Qt::BlockingQueuedConnection,Q_RETURN_ARG(QVariant,target),Q_ARG(QVariant, request));
return target; return target;
} }
@ -386,67 +392,6 @@ void FluHttp::addHeaders(QNetworkRequest* request,const QMap<QString, QVariant>&
} }
} }
void FluHttp::onStart(const QJSValue& callable){
MainThread::post([=](){
QJSValue onStart = callable.property("onStart");
onStart.call();
});
}
void FluHttp::onFinish(const QJSValue& callable){
MainThread::post([=](){
QJSValue onFinish = callable.property("onFinish");
onFinish.call();
});
}
void FluHttp::onError(const QJSValue& callable,int status,QString errorString,QString result){
MainThread::post([=](){
QJSValue onError = callable.property("onError");
QJSValueList args;
args<<status<<errorString<<result;
onError.call(args);
});
}
void FluHttp::onSuccess(const QJSValue& callable,QString result){
MainThread::post([=](){
QJSValueList args;
args<<result;
QJSValue onSuccess = callable.property("onSuccess");
onSuccess.call(args);
});
}
void FluHttp::onCache(const QJSValue& callable,QString result){
MainThread::post([=](){
QJSValueList args;
args<<result;
QJSValue onSuccess = callable.property("onCache");
onSuccess.call(args);
});
}
void FluHttp::onDownloadProgress(const QJSValue& callable,qint64 recv, qint64 total){
MainThread::post([=](){
QJSValueList args;
args<<static_cast<double>(recv);
args<<static_cast<double>(total);
QJSValue onDownloadProgress = callable.property("onDownloadProgress");
onDownloadProgress.call(args);
});
}
void FluHttp::onUploadProgress(const QJSValue& callable,qint64 sent, qint64 total){
MainThread::post([=](){
QJSValueList args;
args<<static_cast<double>(sent);
args<<static_cast<double>(total);
QJSValue onUploadProgress = callable.property("onUploadProgress");
onUploadProgress.call(args);
});
}
QString FluHttp::readCache(const QMap<QString, QVariant>& request){ QString FluHttp::readCache(const QMap<QString, QVariant>& request){
auto filePath = getCacheFilePath(request); auto filePath = getCacheFilePath(request);
QString result; QString result;

View File

@ -6,6 +6,21 @@
#include <QFile> #include <QFile>
#include <QNetworkAccessManager> #include <QNetworkAccessManager>
#include "stdafx.h" #include "stdafx.h"
#include <QMutex>
class HttpCallable : public QObject{
Q_OBJECT
QML_NAMED_ELEMENT(HttpCallable)
public:
explicit HttpCallable(QObject *parent = nullptr);
Q_SIGNAL void start();
Q_SIGNAL void finish();
Q_SIGNAL void error(int status,QString errorString,QString result);
Q_SIGNAL void success(QString result);
Q_SIGNAL void cache(QString result);
Q_SIGNAL void downloadProgress(qint64 recv, qint64 total);
Q_SIGNAL void uploadProgress(qint64 recv, qint64 total);
};
class FluHttp : public QObject class FluHttp : public QObject
{ {
@ -21,13 +36,6 @@ private:
void handleReply(QNetworkReply* reply); void handleReply(QNetworkReply* reply);
void addQueryParam(QUrl* url,const QMap<QString, QVariant>& params); void addQueryParam(QUrl* url,const QMap<QString, QVariant>& params);
void addHeaders(QNetworkRequest* request,const QMap<QString, QVariant>& params); void addHeaders(QNetworkRequest* request,const QMap<QString, QVariant>& params);
void onStart(const QJSValue& callable);
void onFinish(const QJSValue& callable);
void onError(const QJSValue& callable,int status,QString errorString,QString result);
void onSuccess(const QJSValue& callable,QString result);
void onCache(const QJSValue& callable,QString result);
void onDownloadProgress(const QJSValue& callable,qint64 recv, qint64 total);
void onUploadProgress(const QJSValue& callable,qint64 recv, qint64 total);
void handleCache(QMap<QString, QVariant> request, const QString& result); void handleCache(QMap<QString, QVariant> request, const QString& result);
QString readCache(const QMap<QString, QVariant>& request); QString readCache(const QMap<QString, QVariant>& request);
bool cacheExists(const QMap<QString, QVariant>& request); bool cacheExists(const QMap<QString, QVariant>& request);
@ -36,12 +44,12 @@ public:
explicit FluHttp(QObject *parent = nullptr); explicit FluHttp(QObject *parent = nullptr);
~FluHttp(); ~FluHttp();
//神坑!!! 如果参数使用QVariantMap会有问题在6.4.3版本中QML一调用就会编译失败。所以改用QMap<QString, QVariant> //神坑!!! 如果参数使用QVariantMap会有问题在6.4.3版本中QML一调用就会编译失败。所以改用QMap<QString, QVariant>
Q_INVOKABLE void get(QString url,QJSValue callable,QMap<QString, QVariant> params= {},QMap<QString, QVariant> headers = {}); Q_INVOKABLE void get(QString url,HttpCallable* callable,QMap<QString, QVariant> params= {},QMap<QString, QVariant> headers = {});
Q_INVOKABLE void post(QString url,QJSValue callable,QMap<QString, QVariant> params= {},QMap<QString, QVariant> headers = {}); Q_INVOKABLE void post(QString url,HttpCallable* callable,QMap<QString, QVariant> params= {},QMap<QString, QVariant> headers = {});
Q_INVOKABLE void postString(QString url,QJSValue callable,QString params = "",QMap<QString, QVariant> headers = {}); Q_INVOKABLE void postString(QString url,HttpCallable* callable,QString params = "",QMap<QString, QVariant> headers = {});
Q_INVOKABLE void postJson(QString url,QJSValue callable,QMap<QString, QVariant> params = {},QMap<QString, QVariant> headers = {}); Q_INVOKABLE void postJson(QString url,HttpCallable* callable,QMap<QString, QVariant> params = {},QMap<QString, QVariant> headers = {});
Q_INVOKABLE void download(QString url,QJSValue callable,QString filePath,QMap<QString, QVariant> params = {},QMap<QString, QVariant> headers = {}); Q_INVOKABLE void download(QString url,HttpCallable* callable,QString filePath,QMap<QString, QVariant> params = {},QMap<QString, QVariant> headers = {});
Q_INVOKABLE void upload(QString url,QJSValue callable,QMap<QString, QVariant> params = {},QMap<QString, QVariant> headers = {}); Q_INVOKABLE void upload(QString url,HttpCallable* callable,QMap<QString, QVariant> params = {},QMap<QString, QVariant> headers = {});
Q_INVOKABLE void cancel(); Q_INVOKABLE void cancel();
private: private:
QList<QPointer<QNetworkReply>> _cacheReply; QList<QPointer<QNetworkReply>> _cacheReply;

View File

@ -6,6 +6,7 @@
#include <QScreen> #include <QScreen>
#include <QColor> #include <QColor>
#include <QFileInfo> #include <QFileInfo>
#include <QDir>
#include <QCryptographicHash> #include <QCryptographicHash>
#include <QTextDocument> #include <QTextDocument>
@ -145,3 +146,7 @@ QString FluTools::fromBase64(QString text)
return QByteArray::fromBase64(text.toUtf8()); return QByteArray::fromBase64(text.toUtf8());
} }
bool FluTools::removeDir(QString dirPath){
QDir qDir(dirPath);
return qDir.removeRecursively();
}

View File

@ -149,21 +149,29 @@ public:
* @param text * @param text
* @return * @return
*/ */
QString md5(QString text); Q_INVOKABLE QString md5(QString text);
/** /**
* @brief toBase64 * @brief toBase64
* @param text * @param text
* @return * @return
*/ */
QString toBase64(QString text); Q_INVOKABLE QString toBase64(QString text);
/** /**
* @brief fromBase64 * @brief fromBase64
* @param text * @param text
* @return * @return
*/ */
QString fromBase64(QString text); Q_INVOKABLE QString fromBase64(QString text);
/**
* @brief removeDir
* @param dirPath
* @return
*/
Q_INVOKABLE bool removeDir(QString dirPath);
}; };

View File

@ -38,6 +38,7 @@ void FluentUIPlugin::registerTypes(const char *uri)
qmlRegisterType<FluColorSet>(uri,major,minor,"FluColorSet"); qmlRegisterType<FluColorSet>(uri,major,minor,"FluColorSet");
qmlRegisterType<FluHttpInterceptor>(uri,major,minor,"FluHttpInterceptor"); qmlRegisterType<FluHttpInterceptor>(uri,major,minor,"FluHttpInterceptor");
qmlRegisterType<FluHttp>(uri,major,minor,"FluHttp"); qmlRegisterType<FluHttp>(uri,major,minor,"FluHttp");
qmlRegisterType<HttpCallable>(uri,major,minor,"HttpCallable");
qmlRegisterUncreatableMetaObject(Fluent_Awesome::staticMetaObject, uri,major,minor,"FluentIcons", "Access to enums & flags only"); qmlRegisterUncreatableMetaObject(Fluent_Awesome::staticMetaObject, uri,major,minor,"FluentIcons", "Access to enums & flags only");
qmlRegisterUncreatableMetaObject(FluThemeType::staticMetaObject, uri,major,minor,"FluThemeType", "Access to enums & flags only"); qmlRegisterUncreatableMetaObject(FluThemeType::staticMetaObject, uri,major,minor,"FluThemeType", "Access to enums & flags only");
qmlRegisterUncreatableMetaObject(FluPageType::staticMetaObject, uri,major,minor,"FluPageType", "Access to enums & flags only"); qmlRegisterUncreatableMetaObject(FluPageType::staticMetaObject, uri,major,minor,"FluPageType", "Access to enums & flags only");