当前位置:   article > 正文

UE Http笔记_ue5 onrequestprogress()

ue5 onrequestprogress()

c++参考链接

UE4 开发如何使用 Http 请求_wx61ae2f5191643的技术博客_51CTO博客

虚幻引擎:UEC++如何对JSON文件进行读写?-CSDN博客

UE4 HTTP使用

官方免费插件

VaRest

在代码插件创建的VaRest - 虚幻引擎商城

UE5在蓝图中使用Varest插件Get,Post两种常见请求方式_慢慢沉的博客-CSDN博客

UE4使用VaRest插件请求httpAPI以及解析json格式数据_ue4 varest-CSDN博客

*请求以后接收Json一定要注意这里.不要用错对象了.我在这卡了10分钟才找到问题出在哪

示例代码

里面有部分是我测试Http下载文件的代码.所以实际效果很乱.自行理解删减

  1. xxx..Build.cs
  2. "HTTP",
  3. "Json",
  4. "JsonUtilities"
  1. .h
  2. #pragma once
  3. #include "CoreMinimal.h"
  4. #include "Kismet/BlueprintAsyncActionBase.h"
  5. #include "Interfaces/IHttpRequest.h"
  6. #include "AsyncHttpObject.generated.h"
  7. #pragma region One
  8. DECLARE_DYNAMIC_MULTICAST_DELEGATE_ThreeParams(FDownloadProgressDelegate,
  9. const int32&, ReceivedDataInBytes,
  10. const int32&, TotalDataInBytes,
  11. const TArray<uint8>&, BinaryData
  12. );
  13. DECLARE_DYNAMIC_MULTICAST_DELEGATE(FDownloadDelegate);
  14. #pragma endregion
  15. #pragma region Two
  16. UENUM(BlueprintType)
  17. enum class EPTRequestVerb : uint8
  18. {
  19. GET,
  20. POST
  21. };
  22. #pragma endregion
  23. /**
  24. *
  25. */
  26. UCLASS()
  27. class PIECETOGETHERTOOLS_API UAsyncHttpObject : public UBlueprintAsyncActionBase
  28. {
  29. GENERATED_BODY()
  30. public:
  31. #pragma region One
  32. UFUNCTION(BlueprintCallable, Category = "Vince | AsyncHttp", meta = (BlueprintInternalUseOnly = "true"))
  33. static UAsyncHttpObject* AsyncHttpDownload(const FString& URL, FString fileSavePath, FString ileSaveName);
  34. void DownloadRequestStart(const FString& url);
  35. void DownloadRequestHandle(FHttpRequestPtr request, FHttpResponsePtr response, bool bWasSuccessful);
  36. void DownloadProgress(FHttpRequestPtr request, int32 bytesSent, int32 bytesReceived);
  37. //输出节点
  38. UPROPERTY(BlueprintAssignable, Category = "Vince | AsyncHttp")
  39. FDownloadProgressDelegate OnProgressUpdate; //最好把有参数的放在前面,不然参数在蓝图节点有时候被吃掉了
  40. //输出节点
  41. UPROPERTY(BlueprintAssignable, Category = "Vince | AsyncHttp")
  42. FDownloadDelegate OnSucc;
  43. //输出节点
  44. UPROPERTY(BlueprintAssignable, Category = "Vince | AsyncHttp")
  45. FDownloadDelegate OnFailed;
  46. #pragma endregion
  47. #pragma region Two
  48. UFUNCTION(BlueprintCallable, Category = "Vince | AsyncHttp", meta = (BlueprintInternalUseOnly = "true"))
  49. static UAsyncHttpObject* ConnectAsyncHttp(EPTRequestVerb verb, const FString& URL);
  50. FString MassageBody = TEXT("");
  51. void AsyncRequestHandle(FHttpRequestPtr request, FHttpResponsePtr response, bool bWasSuccessful);
  52. #pragma endregion
  1. .cpp
  2. // Fill out your copyright notice in the Description page of Project Settings.
  3. #include "AsyncHttpObject.h"
  4. #include "HttpModule.h"
  5. #include "Interfaces/IHttpResponse.h"
  6. #include "Misc/Paths.h"
  7. #include "HAL/PlatformFileManager.h"
  8. #include "GenericPlatform/GenericPlatformFile.h"
  9. #pragma region One
  10. //存储目录
  11. FString FileSavePath =TEXT("");
  12. //存储名字
  13. FString FileSaveName = TEXT("");
  14. UAsyncHttpObject* UAsyncHttpObject::AsyncHttpDownload(const FString& URL, FString fileSavePath, FString fileSaveName)
  15. {
  16. UAsyncHttpObject* AsyncHttpObject = NewObject<UAsyncHttpObject>();
  17. AsyncHttpObject->DownloadRequestStart(URL);
  18. FileSavePath = fileSavePath;
  19. FileSaveName = fileSaveName;
  20. return AsyncHttpObject;
  21. }
  22. //开始请求下载
  23. void UAsyncHttpObject::DownloadRequestStart(const FString& url)
  24. {
  25. TSharedRef<IHttpRequest, ESPMode::ThreadSafe> request = FHttpModule::Get().CreateRequest();
  26. request->SetVerb("GET");
  27. request->SetURL(url);
  28. request->OnProcessRequestComplete().BindUObject(this, &UAsyncHttpObject::DownloadRequestHandle); //请求回调
  29. request->OnRequestProgress().BindUObject(this, &UAsyncHttpObject::DownloadProgress);// 下载进度
  30. request->ProcessRequest();
  31. RemoveFromRoot(); // 手动GC
  32. }
  33. 请求回调
  34. void UAsyncHttpObject::DownloadRequestHandle(FHttpRequestPtr request, FHttpResponsePtr response, bool bWasSuccessful)
  35. {
  36. RemoveFromRoot();
  37. if (bWasSuccessful && response.IsValid() && EHttpResponseCodes::IsOk(response->GetResponseCode()))
  38. {
  39. if (response->GetContentLength() > 0) {
  40. TArray<uint8> EmptyData;
  41. OnProgressUpdate.Broadcast(response->GetContentLength(), response->GetContentLength(), EmptyData);
  42. }
  43. //FString FileSavePath = FPaths::ProjectDir() + "/download/gameplay.png";
  44. //下载返回类型设置
  45. FString sType, SLeft, SRight;
  46. sType = response->GetHeader(TEXT("Content-Type"));
  47. sType.Split("/",&SLeft,&SRight);
  48. FileSaveName.Append(FString::Printf(TEXT(".%s"), *SRight)) ;
  49. //组合 存储地址
  50. FileSavePath = FPaths::Combine(FileSavePath, FileSaveName);
  51. FString Path, Filename, Extension;
  52. FPaths::Split(FileSavePath, Path, Filename, Extension);
  53. IPlatformFile& PlatformFile = FPlatformFileManager::Get().GetPlatformFile();
  54. if (!PlatformFile.DirectoryExists(*Path))
  55. {
  56. if (!PlatformFile.CreateDirectoryTree(*Path))
  57. {
  58. UE_LOG(LogTemp, Error, TEXT("Create Directory Failed!"));
  59. OnFailed.Broadcast();
  60. return;
  61. }
  62. }
  63. IFileHandle* FileHandle = PlatformFile.OpenWrite(*FileSavePath);
  64. if (FileHandle)
  65. {
  66. FileHandle->Write(response->GetContent().GetData(), response->GetContentLength());
  67. delete FileHandle;
  68. OnSucc.Broadcast();
  69. return;
  70. }
  71. else {
  72. UE_LOG(LogTemp, Error, TEXT("Save File Failed!"));
  73. OnFailed.Broadcast();
  74. return;
  75. }
  76. }
  77. UE_LOG(LogTemp, Error, TEXT("download File Failed!"));
  78. OnFailed.Broadcast();
  79. return;
  80. }
  81. // 下载进度
  82. void UAsyncHttpObject::DownloadProgress(FHttpRequestPtr request, int32 bytesSent, int32 bytesReceived)
  83. {
  84. if (request->GetResponse()->GetContentLength() > 0)
  85. {
  86. TArray<uint8> EmptyData;
  87. OnProgressUpdate.Broadcast(bytesReceived, request->GetResponse()->GetContentLength(), EmptyData);
  88. }
  89. }
  90. UAsyncHttpObject* UAsyncHttpObject::ConnectAsyncHttp(EPTRequestVerb verb, const FString& URL)
  91. {
  92. UAsyncHttpObject* AsyncHttpObject = NewObject<UAsyncHttpObject>();
  93. AsyncHttpObject->MassageBody = "";
  94. if (URL.IsEmpty())
  95. {
  96. // AsyncHttpObject->OnFailed.Broadcast("URL Is Null");
  97. }
  98. TSharedRef<IHttpRequest, ESPMode::ThreadSafe> request = FHttpModule::Get().CreateRequest();
  99. switch (verb)
  100. {
  101. case EPTRequestVerb::GET:
  102. //设置请求方式
  103. request->SetVerb(TEXT("GET"));
  104. //设置头
  105. request->SetHeader(TEXT("Content-Type"), TEXT("application/json;charset=utf-8"));
  106. break;
  107. case EPTRequestVerb::POST:
  108. request->SetVerb(TEXT("POST"));
  109. request->SetHeader(TEXT("Content-Type"), TEXT("application/x - www-form-urlencoded"));
  110. break;
  111. default:
  112. break;
  113. }
  114. //设置URL
  115. request->SetURL(URL);
  116. //绑定回调
  117. request->OnProcessRequestComplete().BindUObject(AsyncHttpObject, &UAsyncHttpObject::AsyncRequestHandle); //请求回调
  118. request->OnRequestProgress().BindUObject(AsyncHttpObject, &UAsyncHttpObject::DownloadProgress);// 下载进度
  119. 内容
  120. TSharedRef<FJsonObject> pJsonObject = MakeShared<FJsonObject>();
  121. TSharedRef<FJsonObject> pJsonObject1 = MakeShared<FJsonObject>();
  122. //
  123. //pJsonObject->SetStringField("TD", URL);
  124. //pJsonObject->SetStringField("TD1", "123");
  125. //
  126. pJsonObject1->SetObjectField("TDB",pJsonObject);
  127. //FString OutputString;
  128. //TSharedRef<TJsonWriter<>> Writer = TJsonWriterFactory<>::Create(&OutputString);
  129. //FJsonSerializer::Serialize(pJsonObject1, Writer);
  130. Json内容设置
  131. //request->SetContentAsString(OutputString);
  132. //GEngine->AddOnScreenDebugMessage(-1, 10.0f, FColor::Yellow, OutputString, false);
  133. //请求
  134. request->ProcessRequest();
  135. AsyncHttpObject->RemoveFromRoot(); // 手动GC
  136. return AsyncHttpObject;
  137. }
  138. void UAsyncHttpObject::AsyncRequestHandle(FHttpRequestPtr request, FHttpResponsePtr response, bool bWasSuccessful)
  139. {
  140. RemoveFromRoot(); // 手动GC
  141. if (bWasSuccessful && response.IsValid() && EHttpResponseCodes::IsOk(response->GetResponseCode()))
  142. {
  143. // 获得返回的json数据
  144. TSharedRef<TJsonReader<TCHAR>> JsonReader = TJsonReaderFactory<TCHAR>::Create(response->GetContentAsString());
  145. // 把FString转成TCHAR
  146. TCHAR* serializedChar = response->GetContentAsString().GetCharArray().GetData();
  147. // 解决中文乱码问题,服务端也是utf-8
  148. TCHAR_TO_UTF8(serializedChar);
  149. FString myData(serializedChar);
  150. // 创建Json对象
  151. TSharedPtr<FJsonObject> JsonObject;
  152. // 反序列化json
  153. bool bIsOk = FJsonSerializer::Deserialize(JsonReader, JsonObject);
  154. // 判断是否反序列化成功
  155. if (bIsOk)
  156. {
  157. FString data = JsonObject->GetStringField("city");
  158. //FWHelper::Debug(data);
  159. UE_LOG(LogTemp, Warning, TEXT("%s"), *data);
  160. UE_LOG(LogTemp, Warning, TEXT("%s"), *myData);
  161. FString OutputString;
  162. TSharedRef<TJsonWriter<TCHAR, TPrettyJsonPrintPolicy<TCHAR>>> Writer = TJsonWriterFactory<TCHAR, TPrettyJsonPrintPolicy<TCHAR>>::Create(&OutputString);
  163. FJsonSerializer::Serialize(JsonObject.ToSharedRef(), Writer); //Serialize:把内存中的对象转为便于存储和传输的数据
  164. //打印
  165. UE_LOG(LogNet, Warning, TEXT("output 1:\n%s"), *OutputString);
  166. TSharedPtr<FJsonObject, ESPMode::ThreadSafe> Object = JsonObject->GetObjectField(TEXT("name"));
  167. TSharedPtr<FJsonObject, ESPMode::ThreadSafe> ObjectField = Object->GetObjectField(TEXT("realtime"));
  168. FString StringField = ObjectField->GetStringField("text");
  169. }
  170. }
  171. }
  172. #pragma endregion
  173. //void UAsyncHttpObject::XieJson(FString& outjsonStr, const UObject* WorldContextObject)
  174. //{
  175. // // 声明一个存储Json内容的字符串
  176. // FString JsonStr;
  177. // //GetJSONStr(JsonStr,WorldContextObject);
  178. //
  179. // // 创建一个Json编写器
  180. // TSharedRef<TJsonWriter<TCHAR, TCondensedJsonPrintPolicy<TCHAR>>> JsonWriter = TJsonWriterFactory<TCHAR, TCondensedJsonPrintPolicy<TCHAR>>::Create(&JsonStr);
  181. // //TSharedRef<TJsonWriter<>> JsonWriter = TJsonWriterFactory<>::Create(&JsonStr);
  182. //
  183. // // 声明Json对象写入开始
  184. // JsonWriter->WriteObjectStart();
  185. // JsonWriter->WriteValue(TEXT("Time"), TEXT("21"));
  186. //
  187. // // 声明Json数组写入开始
  188. // JsonWriter->WriteArrayStart(TEXT("Data"));
  189. // for (int i = 0; i < 2; i++)
  190. // {
  191. // JsonWriter->WriteObjectStart();
  192. // JsonWriter->WriteValue(TEXT("key"), i);
  193. // JsonWriter->WriteObjectEnd();
  194. // }
  195. // JsonWriter->WriteArrayEnd();
  196. //
  197. // JsonWriter->WriteObjectEnd();
  198. // // 停止写入
  199. // JsonWriter->Close();
  200. //
  201. // UE_LOG(LogTemp, Warning, TEXT("%s"), *JsonStr);
  202. // outjsonStr = JsonStr;
  203. //
  204. // GEngine->AddOnScreenDebugMessage(-1, 10.0f, FColor::Yellow, outjsonStr, false);
  205. //}
写入Http请求内容示例

写入Http请求Json内容我自己测试的可以有2种习惯.看自己习惯.c++能力有限.可能描述有误.自行理解把.

  1. 第一种直接给 FJsonObject 直接写入 .最后在转成Fstring
  2. 内容
  3. TSharedRef<FJsonObject> pJsonObject = MakeShared<FJsonObject>();
  4. TSharedRef<FJsonObject> pJsonObject1 = MakeShared<FJsonObject>();
  5. pJsonObject->SetStringField("TD", URL);
  6. pJsonObject->SetStringField("TD1", "123");
  7. //pJsonObject1->SetObjectField("TDB",pJsonObject);
  8. FString OutputString;
  9. TSharedRef<TJsonWriter<>> Writer = TJsonWriterFactory<>::Create(&OutputString);
  10. FJsonSerializer::Serialize(pJsonObject1, Writer);
  11. //Json内容设置
  12. request->SetContentAsString(OutputString);
  13. GEngine->AddOnScreenDebugMessage(-1, 10.0f, FColor::Yellow, OutputString, false);

  1. 第二种 创建一个Json编写器 直接编写Json.
  2. .h
  3. UFUNCTION(BlueprintCallable, Category = "Vince | AsyncHttp", meta = (WorldContext = "WorldContextObject"))
  4. static void XieJson(FString& outjsonStr, const UObject* WorldContextObject);
  5. .cpp
  6. void UPieceTogetherToolsBPLibrary::XieJson(FString& outjsonStr, const UObject* WorldContextObject)
  7. {
  8. // 声明一个存储Json内容的字符串
  9. FString JsonStr;
  10. //GetJSONStr(JsonStr,WorldContextObject);
  11. // 创建一个Json编写器
  12. TSharedRef<TJsonWriter<TCHAR, TCondensedJsonPrintPolicy<TCHAR>>> JsonWriter = TJsonWriterFactory<TCHAR, TCondensedJsonPrintPolicy<TCHAR>>::Create(&JsonStr);
  13. //TSharedRef<TJsonWriter<>> JsonWriter = TJsonWriterFactory<>::Create(&JsonStr);
  14. // 声明Json对象写入开始
  15. JsonWriter->WriteObjectStart();
  16. JsonWriter->WriteValue(TEXT("Time"), TEXT("21"));
  17. // 声明Json数组写入开始
  18. JsonWriter->WriteArrayStart(TEXT("Data"));
  19. for (int i = 0; i < 2; i++)
  20. {
  21. JsonWriter->WriteValue(TEXT("key"), i);
  22. }
  23. JsonWriter->WriteArrayEnd();
  24. JsonWriter->WriteObjectEnd();
  25. // 停止写入
  26. JsonWriter->Close();
  27. UE_LOG(LogTemp, Warning, TEXT("%s"), *JsonStr);
  28. outjsonStr = JsonStr;
  29. GEngine->AddOnScreenDebugMessage(-1, 10.0f, FColor::Yellow, outjsonStr, false);
  30. }
Http接收回调解析数据示例

  1. .cpp
  2. // 获得返回的json数据
  3. TSharedRef<TJsonReader<TCHAR>> JsonReader = TJsonReaderFactory<TCHAR>::Create(response->GetContentAsString());
  4. // 把FString转成TCHAR
  5. TCHAR* serializedChar = response->GetContentAsString().GetCharArray().GetData();
  6. // 解决中文乱码问题,服务端也是utf-8
  7. TCHAR_TO_UTF8(serializedChar);
  8. FString myData(serializedChar);
  9. // 创建Json对象
  10. TSharedPtr<FJsonObject> JsonObject;
  11. // 反序列化json
  12. bool bIsOk = FJsonSerializer::Deserialize(JsonReader, JsonObject);
  13. // 判断是否反序列化成功
  14. if (bIsOk)
  15. {
  16. FString data = JsonObject->GetStringField("city");
  17. //FWHelper::Debug(data);
  18. UE_LOG(LogTemp, Warning, TEXT("%s"), *data);
  19. UE_LOG(LogTemp, Warning, TEXT("%s"), *myData);
  20. FString OutputString;
  21. TSharedRef<TJsonWriter<TCHAR, TPrettyJsonPrintPolicy<TCHAR>>> Writer = TJsonWriterFactory<TCHAR, TPrettyJsonPrintPolicy<TCHAR>>::Create(&OutputString);
  22. FJsonSerializer::Serialize(JsonObject.ToSharedRef(), Writer); //Serialize:把内存中的对象转为便于存储和传输的数据
  23. //打印
  24. UE_LOG(LogNet, Warning, TEXT("output 1:\n%s"), *OutputString);
  25. TSharedPtr<FJsonObject, ESPMode::ThreadSafe> Object = JsonObject->GetObjectField(TEXT("name"));
  26. TSharedPtr<FJsonObject, ESPMode::ThreadSafe> ObjectField = Object->GetObjectField(TEXT("realtime"));
  27. FString StringField = ObjectField->GetStringField("text");
  28. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/AllinToyou/article/detail/91175
推荐阅读
相关标签
  

闽ICP备14008679号