ue中http
#pragma once #include "CoreMinimal.h" #include "GameFramework/Actor.h" #include "Http.h" #include "Runtime/Core/Public/Modules/ModuleManager.h" #include "Runtime/Core/Public/Misc/FileHelper.h" #include "Runtime/Core/Public/Misc/Paths.h" #include "Runtime/Core/Public/HAL/PlatformFilemanager.h" #include "MyHttpActor.generated.h" DECLARE_DYNAMIC_DELEGATE_OneParam(FHttpDownLoadSuccess2, FString, DownLoadContont); DECLARE_DYNAMIC_DELEGATE_OneParam(FHttpDownLoadFailed2, FString, ErrorMsg); UCLASS() class HOTUPDATETEST_API AMyHttpActor : public AActor { GENERATED_BODY() public: AMyHttpActor(); protected: virtual void BeginPlay() override; UFUNCTION() void OnSuccess(FString content); UFUNCTION() void OnFailed(FString content); public: virtual void Tick(float DeltaTime) override; }; class HOTUPDATETEST_API NetWorkHelper { public: //一般请求模块 void HttpRequest(FString &URL, bool isPost, FString params, FHttpDownLoadSuccess2 OnSuccess, FHttpDownLoadFailed2 OnFailed); void HttpRequestComplete(FHttpRequestPtr Request, FHttpResponsePtr Response, bool bWasSuccessful, FHttpDownLoadSuccess2 OnSuccess, FHttpDownLoadFailed2 OnFailed); //上传模块 void HttpUploadFileByArray(FString &URL, TArray<uint8>& rawData, FHttpDownLoadSuccess2 OnSuccess, FHttpDownLoadFailed2 OnFailed); void HttpUploadFileByString(FString &URL, FString rawData, FString filename, FHttpDownLoadSuccess2 OnSuccess, FHttpDownLoadFailed2 OnFailed); void HttpUploadComplete(FHttpRequestPtr Request, FHttpResponsePtr Response, bool bWasSuccessful, FHttpDownLoadSuccess2 OnSuccess, FHttpDownLoadFailed2 OnFailed); //下载模块 static FString savePath; void HttpDownload(const FString& Url, FString& SavePath, FHttpDownLoadSuccess2 OnSuccess, FHttpDownLoadFailed2 OnFailed); void HttpDownloadComplete(FHttpRequestPtr Request, FHttpResponsePtr Response, bool bWasSuccessful, FHttpDownLoadSuccess2 OnSuccess, FHttpDownLoadFailed2 OnFailed); void HttpDownloadProgress(FHttpRequestPtr Request, int32 BytesSent, int32 BytesReceived); };
#include "MyHttpActor.h" AMyHttpActor::AMyHttpActor() { PrimaryActorTick.bCanEverTick = true; } void AMyHttpActor::BeginPlay() { Super::BeginPlay(); int flag = 4; if (flag == 1) { FString url = FString("http://localhost/Handler1.ashx"); //get: FString tparams = FString::Printf(TEXT("username=%s&password=%s"), *FString("zwh"), *FString("123"));
//post: FString::Printf(TEXT("{\"username\":\"%s\",\"password\":\"%s\"}"), *FString("zwh"), *FString("123")); FHttpDownLoadSuccess2 onSuccess; onSuccess.BindUFunction(this, FName("OnSuccess")); FHttpDownLoadFailed2 onFailed; onFailed.BindUFunction(this, FName("OnFailed")); TSharedPtr<NetWorkHelper> networkHelper = MakeShareable(new NetWorkHelper()); networkHelper.Get()->HttpRequest(url, true, tparams, onSuccess, onFailed); } else if (flag == 2) { FString url = FString("http://localhost/Handler2.ashx?filename=%s"); FString fileName = FGenericPlatformHttp::UrlEncode("1.jpg"); url = FString::Printf(*url, *fileName); TArray<uint8> binrary_data; FString path = FString("D:/UE4/ueProjects/HotUpdateTest/images/" + fileName); FFileHelper::LoadFileToArray(binrary_data, *path); FHttpDownLoadSuccess2 onSuccess; onSuccess.BindUFunction(this, FName("OnSuccess")); FHttpDownLoadFailed2 onFailed; onFailed.BindUFunction(this, FName("OnFailed")); TSharedPtr<NetWorkHelper> networkHelper = MakeShareable(new NetWorkHelper()); networkHelper.Get()->HttpUploadFileByArray(url, binrary_data, onSuccess, onFailed); } else if (flag == 3) { //得出结论:文本类型适合用LoadFileToString,而其他复杂的文件类型,例如jpg,适合用LoadFileToArray //因为复杂的文件类型得出的string内容是错误的 //所以LoadFileToArray适用于任何类型 FString url = FString("http://localhost/Handler2.ashx"); FString fileName = "1.txt"; FString content; FString path = FString("D:/UE4/ueProjects/HotUpdateTest/images/" + fileName); FFileHelper::LoadFileToString(content, *path); UE_LOG(LogTemp, Log, TEXT("string content =%s"), *content); FHttpDownLoadSuccess2 onSuccess; onSuccess.BindUFunction(this, FName("OnSuccess")); FHttpDownLoadFailed2 onFailed; onFailed.BindUFunction(this, FName("OnFailed")); TSharedPtr<NetWorkHelper> networkHelper = MakeShareable(new NetWorkHelper()); networkHelper.Get()->HttpUploadFileByString(url, content, fileName, onSuccess, onFailed); } else if (flag == 4) { FString url = FString("http://localhost/images/1.jpg"); FString savePath = FString("D:/1.jpg"); FHttpDownLoadSuccess2 onSuccess; onSuccess.BindUFunction(this, FName("OnSuccess")); FHttpDownLoadFailed2 onFailed; onFailed.BindUFunction(this, FName("OnFailed")); TSharedPtr<NetWorkHelper> networkHelper = MakeShareable(new NetWorkHelper()); networkHelper.Get()->HttpDownload(url, savePath, onSuccess, onFailed); } } void AMyHttpActor::Tick(float DeltaTime) { Super::Tick(DeltaTime); } void AMyHttpActor::OnSuccess(FString content) { UE_LOG(LogTemp, Log, TEXT("request success = %s"), *content); } void AMyHttpActor::OnFailed(FString content) { UE_LOG(LogTemp, Log, TEXT("request error = %s"), *content); } void NetWorkHelper::HttpRequest(FString &URL, bool isPost, FString params, FHttpDownLoadSuccess2 OnSuccess, FHttpDownLoadFailed2 OnFailed) { TSharedRef<class IHttpRequest> HttpRequest = FHttpModule::Get().CreateRequest(); HttpRequest->OnProcessRequestComplete().BindRaw(this, &NetWorkHelper::HttpRequestComplete, OnSuccess, OnFailed); if (isPost) { HttpRequest->SetVerb(TEXT("POST")); HttpRequest->SetContentAsString(params); } else { HttpRequest->SetVerb(TEXT("GET")); URL += FString("?") + params; } HttpRequest->SetURL(URL); HttpRequest->SetHeader(TEXT("Content-Type"), TEXT("application/x-www-form-urlencoded;charset=UTF-8")); HttpRequest->ProcessRequest(); } void NetWorkHelper::HttpRequestComplete(FHttpRequestPtr Request, FHttpResponsePtr Response, bool bWasSuccessful, FHttpDownLoadSuccess2 OnSuccess, FHttpDownLoadFailed2 OnFailed) { if (!bWasSuccessful || !Response.IsValid()) { OnFailed.ExecuteIfBound("NetWork Connect Failed"); return; } if (!EHttpResponseCodes::IsOk(Response->GetResponseCode())) { OnFailed.ExecuteIfBound("NetWork Connect Failed" + FString::FromInt(Response->GetResponseCode())); return; } FString content = Response->GetContentAsString(); OnSuccess.ExecuteIfBound(content); } void NetWorkHelper::HttpUploadFileByArray(FString & URL, TArray<uint8>& rawData, FHttpDownLoadSuccess2 OnSuccess, FHttpDownLoadFailed2 OnFailed) { TSharedRef<class IHttpRequest> HttpRequest = FHttpModule::Get().CreateRequest(); HttpRequest->OnProcessRequestComplete().BindRaw(this, &NetWorkHelper::HttpRequestComplete, OnSuccess, OnFailed); HttpRequest->SetVerb(TEXT("POST")); HttpRequest->SetURL(URL); HttpRequest->SetContent(rawData); HttpRequest->SetHeader(TEXT("Content-Type"), TEXT("multipart/form-data;charset=UTF-8")); HttpRequest->ProcessRequest(); } void NetWorkHelper::HttpUploadFileByString(FString & URL, FString rawData, FString filename, FHttpDownLoadSuccess2 OnSuccess, FHttpDownLoadFailed2 OnFailed) { TSharedRef<class IHttpRequest> HttpRequest = FHttpModule::Get().CreateRequest(); HttpRequest->OnProcessRequestComplete().BindRaw(this, &NetWorkHelper::HttpRequestComplete, OnSuccess, OnFailed); HttpRequest->SetVerb(TEXT("POST")); HttpRequest->SetURL(URL); HttpRequest->SetContentAsString(rawData); HttpRequest->SetHeader(TEXT("Content-Type"), TEXT("multipart/form-data;charset=UTF-8")); HttpRequest->SetHeader(TEXT("filename"), filename); HttpRequest->ProcessRequest(); } void NetWorkHelper::HttpUploadComplete(FHttpRequestPtr Request, FHttpResponsePtr Response, bool bWasSuccessful, FHttpDownLoadSuccess2 OnSuccess, FHttpDownLoadFailed2 OnFailed) { if (!bWasSuccessful || !Response.IsValid()) { OnFailed.ExecuteIfBound("NetWork Connect Failed"); return; } if (!EHttpResponseCodes::IsOk(Response->GetResponseCode())) { OnFailed.ExecuteIfBound("NetWork Connect Failed" + FString::FromInt(Response->GetResponseCode())); return; } FString content = Response->GetContentAsString(); OnSuccess.ExecuteIfBound(content); } FString NetWorkHelper::savePath; void NetWorkHelper::HttpDownload(const FString & Url, FString& SavePath, FHttpDownLoadSuccess2 OnSuccess, FHttpDownLoadFailed2 OnFailed) { savePath = SavePath; TSharedRef< IHttpRequest > HttpRequest = FHttpModule::Get().CreateRequest(); //如果此类继承于UObject,那么可以使用BindUObject来给OnProcessRequestComplete绑定方法 HttpRequest->OnProcessRequestComplete().BindRaw(this, &NetWorkHelper::HttpDownloadComplete, OnSuccess, OnFailed); HttpRequest->SetVerb("GET"); HttpRequest->SetURL(Url); HttpRequest->OnRequestProgress().BindRaw(this, &NetWorkHelper::HttpDownloadProgress); HttpRequest->ProcessRequest(); } void NetWorkHelper::HttpDownloadComplete(FHttpRequestPtr Request, FHttpResponsePtr Response, bool bWasSuccessful, FHttpDownLoadSuccess2 OnSuccess, FHttpDownLoadFailed2 OnFailed) { Request->OnProcessRequestComplete().Unbind(); if (Response.IsValid() && EHttpResponseCodes::IsOk(Response->GetResponseCode())) { IPlatformFile& PlatformFile = FPlatformFileManager::Get().GetPlatformFile(); FString Path, Filename, Extension; FPaths::Split(savePath, Path, Filename, Extension); if (!PlatformFile.DirectoryExists(*Path)) { if (!PlatformFile.CreateDirectoryTree(*Path)) { return; } } IFileHandle* FileHandle = PlatformFile.OpenWrite(*savePath); if (FileHandle) { FileHandle->Write(Response->GetContent().GetData(), Response->GetContentLength()); delete FileHandle; } } } void NetWorkHelper::HttpDownloadProgress(FHttpRequestPtr Request, int32 BytesSent, int32 BytesReceived) { int32 fullSize = Request->GetContentLength(); UE_LOG(LogTemp, Log, TEXT("download percent %d = %d = %d"), BytesReceived, fullSize, BytesSent); }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Web; namespace WebApplication1 { public class Handler2 : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; HttpRequest hr = context.Request; int flag = 1; if (flag == 1) { string username = context.Request.Form["username"]; string password = context.Request.Form["password"]; context.Response.Write(username + "=" + password); } else if (flag == 2) { context.Response.Write("内容长度" + hr.ContentLength + "\n"); string filename = context.Request["filename"]; context.Response.Write("文件名称" + filename + "\n"); using (Stream stream = hr.InputStream) { using (FileStream fs = File.OpenWrite("D:\\" + filename)) { byte[] b = new byte[1024 * 1024 * 2]; int readlength = 0; while ((readlength = stream.Read(b, 0, b.Length)) > 0) { fs.Write(b, 0, readlength); } } } context.Response.Write("文件保存成功"); } else if (flag == 3) { context.Response.Write("内容长度" + hr.ContentLength + "\n"); string filename = hr.Headers["filename"]; context.Response.Write("文件名称" + filename + "\n"); using (Stream stream = hr.InputStream) { using (FileStream fs = File.OpenWrite("D:\\" + filename)) { byte[] b = new byte[1024 * 1024 * 2]; int readlength = 0; while ((readlength = stream.Read(b, 0, b.Length)) > 0) { fs.Write(b, 0, readlength); } } } context.Response.Write("文件保存成功"); } } public bool IsReusable { get { return false; } } } }