IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 网络协议 -> UE4C++ Http下载文件 -> 正文阅读

[网络协议]UE4C++ Http下载文件

成果
在这里插入图片描述
功能:点击一个按钮可以远程下载文件 并看得到进度条

先上代码
.h文件

// Fill out your copyright notice in the Description page of Project Settings.

#pragma once

#include "CoreMinimal.h"
#include "UObject/Object.h"
#include "Interfaces/IHttpRequest.h"
#include "RuntimeFilesDownloaderLibrary.generated.h"

/**
 * 
 */
UENUM(BlueprintType, Category = "Runtime Files Downloader")
enum DownloadResult
{
	SuccessDownloading UMETA(DisplayName = "Success"),
	DownloadFailed UMETA(DisplayName = "Download failed"),
	SaveFailed UMETA(DisplayName = "Save failed"),
	DirectoryCreationFailed UMETA(DisplayName = "Directory creation failed")
};
DECLARE_DYNAMIC_MULTICAST_DELEGATE_ThreeParams(FOnFilesDownloaderProgress, const int32, BytesSent, const int32, BytesReceived,
											   const int32, ContentLength);

/**
 
 */
DECLARE_DYNAMIC_MULTICAST_DELEGATE_OneParam(FOnFilesDownloaderResult, TEnumAsByte < DownloadResult >, Result);

UCLASS()
class DOWNLOAD_API URuntimeFilesDownloaderLibrary : public UObject
{
	GENERATED_BODY()
public:
	UPROPERTY(BlueprintAssignable, Category = "Runtime Files Downloader")
	FOnFilesDownloaderProgress OnProgress;

	/**
	
	 */
	UPROPERTY(BlueprintAssignable, Category = "Runtime Files Downloader")
	FOnFilesDownloaderResult OnResult;

	/**
	
	 */
	UPROPERTY(BlueprintReadOnly, Category = "Runtime Files Downloader")
	FString FileURL;

	/**
	
	 */
	UPROPERTY(BlueprintReadOnly, Category = "Runtime Files Downloader")
	FString FileSavePath;

	/**
	 */
	UFUNCTION(BlueprintCallable, Category = "Runtime Files Downloader")
	static URuntimeFilesDownloaderLibrary* CreateDownloader();

	/**
	
	 */
	UFUNCTION(BlueprintCallable, Category = "Runtime Files Downloader")
	bool DownloadFile(const FString& URL, const FString& SavePath, float TimeOut = 5);
private:
	
	void OnProgress_Internal(FHttpRequestPtr Request, int32 BytesSent, int32 BytesReceived);

	/**
	 *
	 */
	void OnReady_Internal(FHttpRequestPtr Request, FHttpResponsePtr Response, bool bWasSuccessful);
};

.cpp文件

// Fill out your copyright notice in the Description page of Project Settings.


#include "RuntimeFilesDownloaderLibrary.h"
#include "HttpModule.h"
#include "Interfaces/IHttpRequest.h"
#include "Interfaces/IHttpResponse.h"

URuntimeFilesDownloaderLibrary* URuntimeFilesDownloaderLibrary::CreateDownloader()
{
	URuntimeFilesDownloaderLibrary* Downloader = NewObject<URuntimeFilesDownloaderLibrary>();
	Downloader->AddToRoot();
	return Downloader;
}

bool URuntimeFilesDownloaderLibrary::DownloadFile(const FString& URL, const FString& SavePath, float TimeOut)
{
	if (URL.IsEmpty() || SavePath.IsEmpty() || TimeOut <= 0)
	{
		return false;
	}

	FileURL = URL;
	FileSavePath = SavePath;

	//TSharedRef<IHttpRequest, ESPMode::ThreadSafe> HttpRequest = FHttpModule::Get().CreateRequest();

	TSharedPtr<IHttpRequest, ESPMode::ThreadSafe> HttpRequest = FHttpModule::Get().CreateRequest();

	HttpRequest->SetVerb("GET");
	HttpRequest->SetURL(FileURL);
	//HttpRequest->SetTimeout(TimeOut);
	HttpRequest->OnProcessRequestComplete().BindUObject(this, &URuntimeFilesDownloaderLibrary::OnReady_Internal);
	HttpRequest->OnRequestProgress().BindUObject(this, &URuntimeFilesDownloaderLibrary::OnProgress_Internal);

	// Process the request
	HttpRequest->ProcessRequest();

	return true;
}

void URuntimeFilesDownloaderLibrary::OnProgress_Internal(FHttpRequestPtr Request, int32 BytesSent, int32 BytesReceived)
{
	const FHttpResponsePtr Response = Request->GetResponse();
	if (Response.IsValid())
	{
		const int32 FullSize = Response->GetContentLength();
		OnProgress.Broadcast(BytesSent, BytesReceived, FullSize);
	}
}

void URuntimeFilesDownloaderLibrary::OnReady_Internal(FHttpRequestPtr Request, FHttpResponsePtr Response,
                                                      bool bWasSuccessful)
{
	RemoveFromRoot();
	Request->OnProcessRequestComplete().Unbind();

	if (Response.IsValid() && EHttpResponseCodes::IsOk(Response->GetResponseCode()) && bWasSuccessful)
	{
		//
		IPlatformFile& PlatformFile = FPlatformFileManager::Get().GetPlatformFile();

		// 
		FString Path, Filename, Extension;
		FPaths::Split(FileSavePath, Path, Filename, Extension);
		if (!PlatformFile.DirectoryExists(*Path))
		{
			if (!PlatformFile.CreateDirectoryTree(*Path))
			{
				OnResult.Broadcast(DirectoryCreationFailed);
				return;
			}
		}

		// 
		IFileHandle* FileHandle = PlatformFile.OpenWrite(*FileSavePath);
		if (FileHandle)
		{
			// 
			FileHandle->Write(Response->GetContent().GetData(), Response->GetContentLength());
			// 
			delete FileHandle;

			OnResult.Broadcast(SuccessDownloading);
		}
		else
		{
			OnResult.Broadcast(SaveFailed);
		}
	}
	else
	{
		OnResult.Broadcast(DownloadFailed);
	}
}

代码参考的知乎大佬 注意UE4.27 http里

 TSharedRef<IHttpRequest> HttpRequest = FHttpModule::Get().CreateRequest();注意这段代码已经不适用了 根据UE官方源码4.27已经修改成
 		TSharedPtr<IHttpRequest, ESPMode::ThreadSafe> Request = FHttpModule::Get().CreateRequest();

在这里插入图片描述

  网络协议 最新文章
使用Easyswoole 搭建简单的Websoket服务
常见的数据通信方式有哪些?
Openssl 1024bit RSA算法---公私钥获取和处
HTTPS协议的密钥交换流程
《小白WEB安全入门》03. 漏洞篇
HttpRunner4.x 安装与使用
2021-07-04
手写RPC学习笔记
K8S高可用版本部署
mySQL计算IP地址范围
上一篇文章      下一篇文章      查看所有文章
加:2022-05-19 12:04:56  更:2022-05-19 12:05:32 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年5日历 -2024/5/19 9:08:23-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码