In order to start using the HTTP module we first need to modify our Build.cs file to include a few new public dependencies. Specifically Http, Json and JsonUtilities.
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
public class Network1 : ModuleRules
{
public Network1(ReadOnlyTargetRules Target):base(Target)
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, meta = (AllowPrivateAccess = "true"), Category = "HTTP")
UBoxComponent* OverlapComponent;
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, meta = (AllowPrivateAccess = "true"), Category = "HTTP")
UWidgetComponent* ResponseWidgetComponent;
private:
FHttpModule* Http;
};
UCLASS()
class NETWORK1_API AHTTPGETActor : public AActor
{
GENERATED_BODY()
public:
// Sets default values for this actor's properties
AHTTPGETActor();
protected:
// Called when the game starts or when spawned
virtual void BeginPlay() override;
public:
// Called every frame
virtual void Tick(float DeltaTime) override;
UFUNCTION()
void OnBeginOverlap(UPrimitiveComponent* OverlappedComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult);
/*Assign this function to call when the GET request processes sucessfully*/
void OnGetUsersResponse(FHttpRequestPtr Request, FHttpResponsePtr Response, bool bWasSuccessful);
void OnGetUserByUsernameResponse(FHttpRequestPtr Request, FHttpResponsePtr Response, bool bWasSuccessful);
UFUNCTION()
void SendHTTPGet(FString Username);
private:
void AddUserToWidget(TSharedPtr<FJsonObject> JsonObject);
public:
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, meta = (AllowPrivateAccess = "true"), Category = "HTTP")
UBoxComponent* OverlapComponent;
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, meta = (AllowPrivateAccess = "true"), Category = "HTTP")
UWidgetComponent* ResponseWidgetComponent;
private:
FHttpModule* Http;
};
UCLASS()
class NETWORK1_API AHTTPGETActor : public AActor
{
GENERATED_BODY()
public:
// Sets default values for this actor's properties
AHTTPGETActor();
protected:
// Called when the game starts or when spawned
virtual void BeginPlay() override;
public:
// Called every frame
virtual void Tick(float DeltaTime) override;
UFUNCTION()
void OnBeginOverlap(UPrimitiveComponent* OverlappedComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult);
/*Assign this function to call when the GET request processes sucessfully*/
void OnGetUsersResponse(FHttpRequestPtr Request, FHttpResponsePtr Response, bool bWasSuccessful);
void OnGetUserByUsernameResponse(FHttpRequestPtr Request, FHttpResponsePtr Response, bool bWasSuccessful);
UFUNCTION()
void SendHTTPGet(FString Username);
private:
void AddUserToWidget(TSharedPtr<FJsonObject> JsonObject);
public:
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, meta = (AllowPrivateAccess = "true"), Category = "HTTP")
UBoxComponent* OverlapComponent;
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, meta = (AllowPrivateAccess = "true"), Category = "HTTP")
UWidgetComponent* ResponseWidgetComponent;
private:
FHttpModule* Http;
};
The other property is our reference to the FHttpModule that will be used for all of our network communication with the server. This is available to us by including the “Http.h” header in our Actor.
Let’s step through our functions one by one and see how they all communicate.
First thing is our overlap that is triggered when the character interacts with this Actor as well as the instantiation of our components and the FHttpModule.
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
// Sets default values
AHTTPGETActor::AHTTPGETActor()
{
// Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it.
// Sets default values
AHTTPGETActor::AHTTPGETActor()
{
// Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it.
PrimaryActorTick.bCanEverTick = true;
OverlapComponent = CreateDefaultSubobject<UBoxComponent>(TEXT("Overlap Area"));
SetRootComponent(OverlapComponent);
ResponseWidgetComponent = CreateDefaultSubobject<UWidgetComponent>(TEXT("Response Widget"));
ResponseWidgetComponent->SetupAttachment(OverlapComponent);
Http = &FHttpModule::Get();
}
// Called when the game starts or when spawned
void AHTTPGETActor::BeginPlay()
{
Super::BeginPlay();
OverlapComponent->OnComponentBeginOverlap.AddDynamic(this, &ThisClass::OnBeginOverlap);
}
// Sets default values
AHTTPGETActor::AHTTPGETActor()
{
// Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it.
PrimaryActorTick.bCanEverTick = true;
OverlapComponent = CreateDefaultSubobject<UBoxComponent>(TEXT("Overlap Area"));
SetRootComponent(OverlapComponent);
ResponseWidgetComponent = CreateDefaultSubobject<UWidgetComponent>(TEXT("Response Widget"));
ResponseWidgetComponent->SetupAttachment(OverlapComponent);
Http = &FHttpModule::Get();
}
// Called when the game starts or when spawned
void AHTTPGETActor::BeginPlay()
{
Super::BeginPlay();
OverlapComponent->OnComponentBeginOverlap.AddDynamic(this, &ThisClass::OnBeginOverlap);
}
With our objects all setup we can now proceed to looking at the OnBeginOverlap method as that is the first thing our character will interact with.
In the begin overlap we do a few things. We update our user widget ( HTTPResponseWidget ) that a loading operation has started and we try to retrieve the username of the player that interacted with our component.
We then send the players username over to SendHTTPGet() which will try to determine if it’s a valid username or not and make it’s HTTP calls out to an external service.
Here is where we start creating our request structure for the HTTP GET call. This means we have to provide a URL and depending on the username we either use it to retrieve a single record or instead get all users available to us.
We also create callbacks via OnProcessRequestComplete to two separate methods: OnGetUsersResponse and OnGetUserByUsernameResponse.
This allows us to handle the response structure per each GET call separately and offload the processing of those requests to different components if required.
We also include some custom headers that can be used for things like the Content-Type definition but also for more complex security and authentication situations.
The OnGetUsersResponse method will be processing this JSON Payload which includes an array of elements as part of the response.
Lastly in our OnGetUsersResponse and OnGetUserByUsernameResponse methods we can use the reference to the FHttpRequestPtr and FHttpResponsePtr parameters to determine if our calls were successful and came back with a status code of 200
Additionally we can observe how the JSON structure is parsed by first using the FJsonObjectin combination with the TJsonReader
That’s it, you successfully processed a JSON response from an external service using your Unreal code.
Hope this helps you guys make your own network requests.
If you would like to see more examples check out the video as well as the GitHub project for examples of child classes that move the player and particles around.