Skip to content

Instantly share code, notes, and snippets.

@yexiuph
Last active April 16, 2022 22:45
Show Gist options
  • Save yexiuph/d85ead762a626e5c2e8be890959d80b6 to your computer and use it in GitHub Desktop.
Save yexiuph/d85ead762a626e5c2e8be890959d80b6 to your computer and use it in GitHub Desktop.
HTTP Requests In Unreal Engine C++
// Get
auto request = FHttpModule::Get().CreateRequest();
request->SetURL(FString("http://localhost:3000/api"));
request->ProcessRequest();
request->OnProcessRequestComplete().BindLambda([](FHttpRequestPtr request, FHttpResponsePtr response, bool success) {
try {
if (success) {
// Deserialize the JSON
TSharedPtr<FJsonObject> JsonObject = MakeShareable(new FJsonObject);
TSharedRef<TJsonReader<>> Reader = TJsonReaderFactory<>::Create(response->GetContentAsString());
try {
if (FJsonSerializer::Deserialize(Reader, JsonObject)) {
// Get Data from JSON
FString Data = JsonObject->GetStringField("Data");
FString Msg = JsonObject->GetStringField("Message");
// Print Data
GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Green, Data);
GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Green, Msg);
}
} catch (...) {
// Print Error
GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, TEXT("Error"));
}
} else {
UE_LOG(LogTemp, Warning, TEXT("Request failed: %s"), *response->GetContentAsString());
}
} catch (...) {
UE_LOG(LogTemp, Warning, TEXT("Request failed"));
}
});
// Post
auto request2 = FHttpModule::Get().CreateRequest();
request2->SetURL(FString("http://localhost:3000/api"));
request2->SetVerb("POST");
request2->SetHeader("Content-Type", "application/json");
request2->SetContentAsString("{\"Data\":\"Test\",\"Message\":\"Test\"}");
request2->ProcessRequest();
request2->OnProcessRequestComplete().BindLambda([](FHttpRequestPtr request, FHttpResponsePtr response, bool success) {
try {
if (success) {
// Deserialize the JSON
TSharedPtr<FJsonObject> JsonObject = MakeShareable(new FJsonObject);
TSharedRef<TJsonReader<>> Reader = TJsonReaderFactory<>::Create(response->GetContentAsString());
try {
if (FJsonSerializer::Deserialize(Reader, JsonObject)) {
// Get Data from JSON
FString Data = JsonObject->GetStringField("Data");
FString Msg = JsonObject->GetStringField("Message");
// Print Data
GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Green, Data);
GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Green, Msg);
}
} catch (...) {
// Print Error
GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, TEXT("Error"));
}
} else {
UE_LOG(LogTemp, Warning, TEXT("Request failed: %s"), *response->GetContentAsString());
}
} catch (...) {
UE_LOG(LogTemp, Warning, TEXT("Request failed"));
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment