Skip to content

Instantly share code, notes, and snippets.

@chris-gong
Created February 9, 2022 23:52
Show Gist options
  • Save chris-gong/8b9cd9156ec5ed54c8bd4983722745c8 to your computer and use it in GitHub Desktop.
Save chris-gong/8b9cd9156ec5ed54c8bd4983722745c8 to your computer and use it in GitHub Desktop.
// Copyright Epic Games, Inc. All Rights Reserved.
#include "HttpTestGameMode.h"
#include "HttpTestCharacter.h"
#include "Json.h"
#include "UObject/ConstructorHelpers.h"
AHttpTestGameMode::AHttpTestGameMode()
{
// set default pawn class to our Blueprinted character
static ConstructorHelpers::FClassFinder<APawn> PlayerPawnBPClass(TEXT("/Game/ThirdPersonCPP/Blueprints/ThirdPersonCharacter"));
if (PlayerPawnBPClass.Class != NULL)
{
DefaultPawnClass = PlayerPawnBPClass.Class;
}
}
void AHttpTestGameMode::StartPlay()
{
Super::StartPlay();
FHttpRequestRef Request = FHttpModule::Get().CreateRequest();
/*Request->OnProcessRequestComplete().BindUObject(this, &AHttpTestGameMode::OnResponseReceived);
Request->SetURL("https://jsonplaceholder.typicode.com/posts/1");
Request->SetVerb("GET");
Request->ProcessRequest();*/
TSharedRef<FJsonObject> RequestObj = MakeShared<FJsonObject>();
RequestObj->SetStringField("title", "foo");
FString RequestBody;
TSharedRef<TJsonWriter<>> Writer = TJsonWriterFactory<>::Create(&RequestBody);
FJsonSerializer::Serialize(RequestObj, Writer);
Request->OnProcessRequestComplete().BindUObject(this, &AHttpTestGameMode::OnResponseReceived);
Request->SetURL("https://jsonplaceholder.typicode.com/posts");
Request->SetVerb("POST");
Request->SetHeader("Content-Type", "application/json");
Request->SetContentAsString(RequestBody);
Request->ProcessRequest();
}
void AHttpTestGameMode::OnResponseReceived(FHttpRequestPtr Request, FHttpResponsePtr Response, bool bConnectedSuccessfully)
{
TSharedPtr<FJsonObject> ResponseObj;
TSharedRef<TJsonReader<>> Reader = TJsonReaderFactory<>::Create(Response->GetContentAsString());
FJsonSerializer::Deserialize(Reader, ResponseObj);
UE_LOG(LogTemp, Display, TEXT("Response %s"), *Response->GetContentAsString());
UE_LOG(LogTemp, Display, TEXT("Title: %s"), *ResponseObj->GetStringField("title"));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment