<style>.lazy{display:none}</style> Skip to main content
Tag

engine

Unreal C++ Networking – HTTP GET JSON Request Using REST API

By Networking, Tutorial, Unreal No Comments

Hey guys,

Today we are going to start looking at some new content related to networking operations with the Unreal Engine.

Specifically we are going to review how to make HTTP GET calls from within Unreal to an external REST API.

The project files for this video & article can be found on our GitHub page.

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.

public class Network1 : ModuleRules
{
  public Network1(ReadOnlyTargetRules Target) : base(Target)
  {
    PCHUsage = PCHUsageMode.UseExplicitOrSharedPCHs;

    PublicDependencyModuleNames.AddRange(new string[] { "Core", "CoreUObject", "Engine", "InputCore", "HeadMountedDisplay",
                    "Http", "Json", "JsonUtilities",
                    "UMG" });

    PrivateDependencyModuleNames.AddRange(new string[] { "Slate", "SlateCore" });
  }
}

With these dependencies included we can define our Actor that is going to handle the work of doing the network communication.

In this case we are using an actor that will relay it’s information to a custom UUserWidget that is attached to this actor via a WidgetComponent.

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.

// 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.

void AHTTPGETActor::OnBeginOverlap(UPrimitiveComponent* OverlappedComponent, AActor* OtherActor,
                                   UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult)
{
  if(ResponseWidgetComponent)
  {
    UHTTPResponseWidget* ResponseWidget = Cast<UHTTPResponseWidget>(ResponseWidgetComponent->GetWidget());
    if(ResponseWidget)
    {
      ResponseWidget->ShowLoading(true);

      FString Username;
      ANetwork1Character* Character = Cast<ANetwork1Character>(OtherActor);
      if(Character && !Character->GetUsername().IsEmpty())
      {
        Username = Character->GetUsername();
      }

      SendHTTPGet(Username);
    }
  }
}

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.

void AHTTPGETActor::SendHTTPGet(FString Username)
{
  TSharedRef<IHttpRequest, ESPMode::ThreadSafe> Request = Http->CreateRequest();

  if(Username.IsEmpty())
  {
    Request->OnProcessRequestComplete().BindUObject(this, &ThisClass::OnGetUsersResponse);
    Request->SetURL("http://localhost:8080/jms-api/users");
  }
  else
  {
    Request->OnProcessRequestComplete().BindUObject(this, &ThisClass::OnGetUserByUsernameResponse);
    Request->SetURL(FString::Printf(TEXT("http://localhost:8080/jms-api/user/%s"), *Username));
  }

  Request->SetVerb("GET");
  Request->SetHeader("User-Agent", "X-UnrealEngine-Agent");
  Request->SetHeader("Content-Type", "application/json");
  Request->ProcessRequest();
}

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.

{
  "users": [
    {
      "id": 1,
      "username": "test-user",
      "email": "[email protected]"
    },
    {
      "id": 2,
      "username": "jms-user",
      "email": "[email protected]"
    },
    {
      "id": 3,
      "username": "john.smith",
      "email": "[email protected]"
    }
  ]
}

While the OnGetUserByUsernameResponse will process a single user entity response.

{
  "id": 1,
  "username": "test-user",
  "email": "[email protected]"
}

Now let’s take a look at the implementation details for these two payloads.

void AHTTPGETActor::OnGetUsersResponse(FHttpRequestPtr Request, FHttpResponsePtr Response, bool bWasSuccessful)
{
  TSharedPtr<FJsonObject> JsonObject;

  if(ResponseWidgetComponent)
  {
    UHTTPResponseWidget* ResponseWidget = Cast<UHTTPResponseWidget>(ResponseWidgetComponent->GetWidget());
    if(ResponseWidget)
    {
      ResponseWidget->ShowLoading(false);

      if(Response->GetResponseCode() == 200)
      {
        const FString ResponseBody = Response->GetContentAsString();

        TSharedRef<TJsonReader<>> Reader = TJsonReaderFactory<>::Create(ResponseBody);

        if(FJsonSerializer::Deserialize(Reader, JsonObject))
        {
          TArray<TSharedPtr<FJsonValue>> UserArray = JsonObject->GetArrayField("users");

          for(const TSharedPtr<FJsonValue> UserValue : UserArray)
          {
            AddUserToWidget(UserValue->AsObject());
          }
        }
      }
      else
      {
        // TODO: trigger error
        ResponseWidget->ShowError(Response->GetResponseCode(), "Error occured");
      }
    }
  }
}


void AHTTPGETActor::OnGetUserByUsernameResponse(FHttpRequestPtr Request, FHttpResponsePtr Response, bool bWasSuccessful)
{
  TSharedPtr<FJsonObject> JsonObject;

  if(ResponseWidgetComponent)
  {
    UHTTPResponseWidget* ResponseWidget = Cast<UHTTPResponseWidget>(ResponseWidgetComponent->GetWidget());
    if(ResponseWidget)
    {
      ResponseWidget->ShowLoading(false);

      if(Response->GetResponseCode() == 200)
      {
        const FString ResponseBody = Response->GetContentAsString();

        TSharedRef<TJsonReader<>> Reader = TJsonReaderFactory<>::Create(ResponseBody);

        if(FJsonSerializer::Deserialize(Reader, JsonObject))
        {
          AddUserToWidget(JsonObject);
        }
      }
      else
      {
        // TODO: trigger error
        ResponseWidget->ShowError(Response->GetResponseCode(), "Error occured");
      }
    }
  }
}

void AHTTPGETActor::AddUserToWidget(TSharedPtr<FJsonObject> JsonObject)
{
  const int32 UserId = JsonObject->GetIntegerField("id");
  const FString Username = JsonObject->GetStringField("username");

  UHTTPResponseWidget* ResponseWidget = Cast<UHTTPResponseWidget>(ResponseWidgetComponent->GetWidget());
  if(ResponseWidget)
  {
    ResponseWidget->AddUser(UserId, Username);
  }
}

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 FJsonObject in combination with the TJsonReader

const FString ResponseBody = Response->GetContentAsString(); 
TSharedRef<TJsonReader<>> Reader = TJsonReaderFactory<>::Create(ResponseBody);

This gives us the ability to then get at the individual properties of a JSON response. Specifically since one requires access to an Array.

if(FJsonSerializer::Deserialize(Reader, JsonObject))
{
  TArray<TSharedPtr<FJsonValue>> UserArray = JsonObject->GetArrayField("users");

  for(const TSharedPtr<FJsonValue> UserValue : UserArray)
  {
    AddUserToWidget(UserValue->AsObject());
  }
}

void AHTTPGETActor::AddUserToWidget(TSharedPtr<FJsonObject> JsonObject)
{
  const int32 UserId = JsonObject->GetIntegerField("id");
  const FString Username = JsonObject->GetStringField("username");

  UHTTPResponseWidget* ResponseWidget = Cast<UHTTPResponseWidget>(ResponseWidgetComponent->GetWidget());
  if(ResponseWidget)
  {
    ResponseWidget->AddUser(UserId, Username);
  }
}

By using the various getters ( GetArrayField / GetIntegerField / GetStringField ) we can iterate and access the various properties of our payload.

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.

Unreal Engine C++ Fundamentals – Using Inheritance by moving the player & particles along a spline

By Tutorial, Unreal No Comments

Hey guys,

Today we are going to continue exploring our last tutorial by looking at inheritance and what it takes to refactor our class.

The project files for this video & article can be found on our GitHub page.

The majority of the inheritance work is by creating a base class that our children can derive from which contains the primary logic that all children are always expected to perform.

To do this we are going to take our previous MovingSplineActor class make some of it’s methods virtual and migrate all of it’s Mesh specific logic to a new MeshMovingSplineActor class.

My making our MovingSplineActor functions virtual we provide the child class to override said functions and implement it’s own logic.

Since we need to have our MeshMovingSplineActor do it’s own work on a static mesh that the parent MovingSplineActor those methods need to be accessible otherwise it’s going to cause conflicts in our logic.

UCLASS()
class UE4FUNDAMENTALS14LIVE_API AMovingSplineActor : public AActor
{
  GENERATED_BODY()
  
public:	
  // Sets default values for this actor's properties
  AMovingSplineActor();

protected:
  // Called when the game starts or when spawned
  virtual void BeginPlay() override;

public:	
  // Called every frame
  virtual void Tick(float DeltaTime) override;

  UFUNCTION()
  virtual void ProcessMovementTimeline(float Value);

  UFUNCTION()
  virtual void OnEndMovementTimeline();

  UFUNCTION()
  virtual void TriggerBeginOverlap(UPrimitiveComponent* OverlappedComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult);
  UFUNCTION()
  virtual void TriggerEndOverlap(UPrimitiveComponent* OverlappedComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex);
}

Additionally we need to ensure that the logic we had in our MovingSplineActor is available to our child class. In this case we need to move the SplineLocation and SplineRotation variables out of the initial processing logic and into their own protected variables.

protected:
  FVector StartingSplineLocation;
  FVector CurrentSplineLocation;
  FRotator CurrentSplineRotation;

We can then modify our CPP file to ensure those variables are populated.

void AMovingSplineActor::ProcessMovementTimeline(float Value)
{
  const float SplineLength = SplineComponent->GetSplineLength();

  CurrentSplineLocation = SplineComponent->GetLocationAtDistanceAlongSpline(Value * SplineLength, ESplineCoordinateSpace::World);
  CurrentSplineRotation = SplineComponent->GetRotationAtDistanceAlongSpline(Value * SplineLength, ESplineCoordinateSpace::World);
}

By migrating all of our logic to the MeshMovingSplineActor we need to ensure it inherits from our new parent class. To do this we need to modify the header definitions to change it from AActor.

UCLASS()
class UE4FUNDAMENTALS14LIVE_API AMeshMovingSplineActor : public AMovingSplineActor
{
  GENERATED_BODY()
  
public:	
  // Sets default values for this actor's properties
  AMeshMovingSplineActor();

protected:
  // Called when the game starts or when spawned
  virtual void BeginPlay() override;

public:	
  // Called every frame
  virtual void Tick(float DeltaTime) override;

  virtual void ProcessMovementTimeline(float Value) override;

  UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Spline", meta=(AllowPrivateAccess = "true"))
  UStaticMeshComponent* MeshComponent;
};

With our headers defined we can now migrate the logic of actually moving the spline component into our new child actor.

AMeshMovingSplineActor::AMeshMovingSplineActor()
{
 	// 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;

  MeshComponent = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("Mesh Component"));
  MeshComponent->SetupAttachment(SplineComponent);

  TriggerComponent->SetupAttachment(MeshComponent);
}

// Called when the game starts or when spawned
void AMeshMovingSplineActor::BeginPlay()
{
  Super::BeginPlay();

  MeshComponent->SetWorldLocation(StartingSplineLocation);
}

// Called every frame
void AMeshMovingSplineActor::Tick(float DeltaTime)
{
  Super::Tick(DeltaTime);

}

void AMeshMovingSplineActor::ProcessMovementTimeline(float Value)
{
  Super::ProcessMovementTimeline(Value);

  FRotator SplineRotation = CurrentSplineRotation;
  SplineRotation.Pitch = 0.f;
  MeshComponent->SetWorldLocationAndRotation(CurrentSplineLocation, SplineRotation);
}

If you notice, each override method ends up calling “Super::MethodSignature()” in order to execute the logic in the parent. Since our parent is simply moving the timeline around we don’t have to worry about anything other than the mesh in our timeline.

So that’s it, you just did some inhertiance work by shuffling around a few class definitions.

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.

Unreal Engine C++ Fundamentals – Moving Static Meshes along a Spline Component

By Props, Tutorial, Unreal No Comments

Hey guys,

Today we are going to take a look how to use Spline Components and modify their various properties to allow us to specify custom materials as well as determine how meshes are attached to the spline.

The project files for this video & article can be found on our GitHub page.

Looking at our previous tutorial we know that splines are not terribly hard to work with but there is a bit of magic to having something move along a spline.

The key ingredient in this is the FTimeline. This allows us to keep track of an execution of values across a specific timeframe.

The FTimeline combined with a UCurveFloat gives us all that flexibility. So let’s look at the code to see how this all breaks down.

FTimeline MovementTimeline;

FOnTimelineFloat ProgressFunction; ProgressFunction.BindUFunction(this, TEXT("ProcessMovementTimeline")); MovementTimeline.AddInterpFloat(MovementCurve, ProgressFunction); FOnTimelineEvent OnTimelineFinishedFunction; OnTimelineFinishedFunction.BindUFunction(this, TEXT("OnEndMovementTimeline")); MovementTimeline.SetTimelineFinishedFunc(OnTimelineFinishedFunction); MovementTimeline.SetTimelineLengthMode(TL_LastKeyFrame); if(bAutoActivate) { MovementTimeline.PlayFromStart(); }

Looking over the code we can see that as part of the FTimeline definition we are specifying a function that will be executed during the runtime of the timeline.

UFUNCTION()
void ProcessMovementTimeline(float Value);

As well as a function at will be executed at the end of our timeline.

UFUNCTION()
void OnEndMovementTimeline();

Additionally we need to ensure that our timeline ticks as part of our object. For this we can examine the Tick method.

// Called every frame
void AMovingSplineActor::Tick(float DeltaTime)
{
  Super::Tick(DeltaTime);

  if(MovementTimeline.IsPlaying())
  {
    MovementTimeline.TickTimeline(DeltaTime);	
  }
}

Now let’s take a look at the magic around moving the mesh across the spline. This all happens within our ProcessMovementTimeline method.

void AMovingSplineActor::ProcessMovementTimeline(float Value)
{
  const float SplineLength = SplineComponent->GetSplineLength();

  const FVector CurrentSplineLocation = SplineComponent->GetLocationAtDistanceAlongSpline(Value * SplineLength, ESplineCoordinateSpace::World);
  FRotator CurrentSplineRotation = SplineComponent->GetRotationAtDistanceAlongSpline(Value * SplineLength, ESplineCoordinateSpace::World);

  CurrentSplineRotation.Pitch = 0.f;
  MeshComponent->SetWorldLocationAndRotation(CurrentSplineLocation, CurrentSplineRotation);
}

As you can see the logic is not that scary. We are simply taking the delta time by the lenght of the spline and retrieving that points location and rotation.

This is then applied to our mesh and we prevent the pitch from being corrected so our elevator / platform does not tip as it’s traversing along the spline.

Lastly let’s take a look at the function OnEndMovementTimeline() which is called at the .. you guessed it … end of our timeline.

UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Spline", meta=(EditCondition = "!bRestartOnEndTimeline"))
bool bReverseOnEndTimeline;

UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Spline", meta=(EditCondition = "!bReverseOnEndTimeline"))
bool bRestartOnEndTimeline;
void AMovingSplineActor::OnEndMovementTimeline()
{
  if(bReverseOnEndTimeline)
  {
    MovementTimeline.Reverse();
  }
  else if(bRestartOnEndTimeline)
  {
    MovementTimeline.PlayFromStart();
  }
}

This function is a great spot to put in logic for things like restarting the movement or reversing the movement by injecting some simple properties into our new object.

For further reading about these topics take a look at the following links: