UE4 HTTP使用
本文记录了UE4 HTTP的使用并且以Post为案例。
GET请求 可以访问URI资源
Post传输实体
传输数据
使用json
结构体转json
/**
* Converts from a UStruct to a json string containing an object, using exportText
*
* @param StructDefinition UStruct definition that is looked over for properties
* @param Struct The UStruct instance to copy out of
* @param JsonObject Json Object to be filled in with data from the ustruct
* @param CheckFlags Only convert properties that match at least one of these flags. If 0 check all properties.
* @param SkipFlags Skip properties that match any of these flags
* @param Indent How many tabs to add to the json serializer
* @param ExportCb Optional callback for types we don't understand. This is called right before falling back to the generic ToString()
* @param bPrettyPrint Option to use pretty print (e.g., adds line endings) or condensed print
*
* @return False if any properties failed to write
*/
static bool UStructToJsonObjectString(const UStruct* StructDefinition, const void* Struct, FString& OutJsonString, int64 CheckFlags, int64 SkipFlags, int32 Indent = 0, const CustomExportCallback* ExportCb = nullptr, bool bPrettyPrint = true);
Json转结构体
/**
* Converts from a UStruct to a json string containing an object, using exportText
*
* @param StructDefinition UStruct definition that is looked over for properties
* @param Struct The UStruct instance to copy out of
* @param JsonObject Json Object to be filled in with data from the ustruct
* @param CheckFlags Only convert properties that match at least one of these flags. If 0 check all properties.
* @param SkipFlags Skip properties that match any of these flags
* @param Indent How many tabs to add to the json serializer
* @param ExportCb Optional callback for types we don't understand. This is called right before falling back to the generic ToString()
* @param bPrettyPrint Option to use pretty print (e.g., adds line endings) or condensed print
*
* @return False if any properties failed to write
*/
static bool UStructToJsonObjectString(const UStruct* StructDefinition, const void* Struct, FString& OutJsonString, int64 CheckFlags, int64 SkipFlags, int32 Indent = 0, const CustomExportCallback* ExportCb = nullptr, bool bPrettyPrint = true);
传输使用的结构体
USTRUCT()
struct FRequest_Login {
GENERATED_BODY()
UPROPERTY() FString email;
UPROPERTY() FString password;
FRequest_Login() {}
};
USTRUCT()
struct FResponse_Login {
GENERATED_BODY()
UPROPERTY() int id;
UPROPERTY() FString name;
UPROPERTY() FString hash;
FResponse_Login() {}
};
模块依赖
Before you start make sure you have included the required dependencies.
# Path: Source/YourProject/YourProject.Build.cs
PrivateDependencyModuleNames.AddRange(new string[] { "Http", "Json", "JsonUtilities" });
Httpis our trusty ue4 http implementation.Jsonis the json conversion libraryJsonUtilitieshas theFJsonObjectConverterwe will be using to convert Json data to Struct data
头文件
#include "HttpModule.h"
#include "Interfaces/IHttpResponse.h"
命令发送流程
1、建立一个 TSharedRef
构建一个这样的对象需要使用 HTTPModule
Http = &FHttpModule::Get();
template <typename StructType>
void AHttpService::GetJsonStringFromStruct(StructType FilledStruct, FString& StringOutput) {
FJsonObjectConverter::UStructToJsonObjectString(StructType::StaticStruct(), &FilledStruct, StringOutput, 0, 0);
}
2、然后设置URL,发送目标地点
TSharedRef<IHttpRequest> Request = Http->CreateRequest();
Request->SetURL(“”);
3、给IHttpRequest SetHeader(有时候也可以省略)
Request->SetHeader(TEXT("User-Agent"), TEXT("X-UnrealEngine-Agent"));
Request->SetHeader(TEXT("Content-Type"), TEXT("application/json"));
Request->SetHeader(TEXT("Accepts"), TEXT("application/json"));
Request->SetHeader(AuthorizationHeader, AuthorizationHash);
4、设置POST命令,传递json数据,以字符串发送,如果是GET命令不需要传递content
Request->SetVerb("POST");
Request->SetContentAsString(ContentJsonString);
5、设置HTTP执行完之后的回调
Request->OnProcessRequestComplete().BindUObject(this, &AHttpService::LoginResponse);
绑定的回调的委托类型是一个单播三个参数的委托
DECLARE_DELEGATE_ThreeParams(FHttpRequestCompleteDelegate, FHttpRequestPtr /*Request*/, FHttpResponsePtr /*Response*/, bool /*bConnectedSuccessfully*/);
6、执行这个HTTP,可以看是否执行成功
Request->ProcessRequest();
7、执行完了进入回调
判断是否执行成功
bool AHttpService::ResponseIsValid(FHttpResponsePtr Response, bool bWasSuccessful) {
if (!bWasSuccessful || !Response.IsValid()) return false;
if (EHttpResponseCodes::IsOk(Response->GetResponseCode())) return true;
else {
UE_LOG(LogTemp, Warning, TEXT("Http Response returned error code: %d"), Response->GetResponseCode());
return false;
}
}
template <typename StructType>
void AHttpService::GetStructFromJsonString(FHttpResponsePtr Response, StructType& StructOutput) {
StructType StructData;
FString JsonString = Response->GetContentAsString();
FJsonObjectConverter::JsonObjectStringToUStruct<StructType>(JsonString, &StructOutput, 0, 0);
}
void AHttpService::LoginResponse(FHttpRequestPtr Request, FHttpResponsePtr Response, bool bWasSuccessful) {
if (!ResponseIsValid(Response, bWasSuccessful)) return;
FResponse_Login LoginResponse;
GetStructFromJsonString<FResponse_Login>(Response, LoginResponse);
UE_LOG(LogTemp, Warning, TEXT("Id is: %d"), LoginResponse.id);
UE_LOG(LogTemp, Warning, TEXT("Name is: %s"), *LoginResponse.name);
}
tips:可以通过自己记录一个TMap来维护一个多播的列表让HTTP变成多播的

浙公网安备 33010602011771号