UE4.10 How To Make HTTP GET Request in C++

Introduction Hello dear reader, This tutorial is for anyone who doesn't know how to make HTTP GET calls in C++. There are some requirements that you need to meet in order to understand this tutoria...

Updated over 4 years ago Edit Page Revisions

Introduction

Hello dear reader,

This tutorial is for anyone who doesn't know how to make HTTP GET calls in C++. There are some requirements that you need to meet in order to understand this tutorial.

Requirements

  • Apache Server installation Download -- Contains a bundle of Apache Server, MySQL Database and FTP Server
  • Basic understanding of C++ and OOP Principles
  • Basic understanding of PHP language

Okay that's all you need for now. Let's begin our tutorial.

Creating a new C++ Project

Start Unreal Engine 4 and create a new C++ Project with BASIC CODE option with whatever name it whatever you want. This file open Visual Studio 2015 and compile your game via Build->Build [ProjectName]

After the project compiles open UE4 and load your project.

Creating a new Actor

Let's create the HTTP GET functionality in an Actor

'' Note: You can create it in a separate C++ component and use it wherever you want but I will leave that for you.''

So let's add our new Actor:

File->New C++ class-> Select Actor as parent and Create

Wait for the engine to recompile new code and open up Visual Studio with your newly created C++ Actor.

Great job so far!

Adding dependencies for HTTP and JSON

When your Visual Studio loads, in your game project source files find the filename called: "ProjectName.Build.cs"

Open it and you will see this line:

PublicDependencyModuleNames.AddRange(new string[] { "Core", "CoreUObject", "Engine", "InputCore"});

We will be adding 3 things: "Http", "Json", "JsonUtilities"

Change it so it looks like:

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

Next, in your Project/Saved/Config/Engine.ini file you need to add the following section to setup the default values for the HTTP Request Module:

[HTTP]
HttpTimeout=300
HttpConnectionTimeout=-1
HttpReceiveTimeout=-1
HttpSendTimeout=-1
HttpMaxConnectionsPerServer=16
bEnableHttp=true
bUseNullHttp=false
HttpDelayTime=0

We are done here. Let's get to coding now.

[ActorName].h

// Fill out your copyright notice in the Description page of Project Settings.

#pragma once

#include "GameFramework/Actor.h"
#include "Runtime/Online/HTTP/Public/Http.h"
#include "HttpActor.generated.h"

UCLASS()
class CPPPROJECT_API AHttpActor : public AActor
{
    GENERATED_BODY()
    
public: 
    FHttpModule* Http;

    /* The actual HTTP call */
    UFUNCTION()
    void MyHttpCall();

    /*Assign this function to call when the GET request processes sucessfully*/
    void OnResponseReceived(FHttpRequestPtr Request, FHttpResponsePtr Response, bool bWasSuccessful);

    // Sets default values for this actor's properties
    AHttpActor(const class FObjectInitializer& ObjectInitializer);

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

We include the HTTP libraries and assign some functions here. The comments explain what happens.

[ActorName].cpp

// Fill out your copyright notice in the Description page of Project Settings.

#include "CPPProject.h"
#include "HttpActor.h"

// Sets default values
AHttpActor::AHttpActor(const class FObjectInitializer& ObjectInitializer)
    : Super(ObjectInitializer)
{
    //When the object is constructed, Get the HTTP module
    Http = &FHttpModule::Get();
}

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

/*Http call*/
void AHttpActor::MyHttpCall()
{
    TSharedRef Request = Http->CreateRequest();
    Request->OnProcessRequestComplete().BindUObject(this, &AHttpActor::OnResponseReceived);
    //This is the url on which to process the request
    Request->SetURL("http://localhost:8081/WebApi/getint.php");
    Request->SetVerb("GET");
    Request->SetHeader(TEXT("User-Agent"), "X-UnrealEngine-Agent");
    Request->SetHeader("Content-Type", TEXT("application/json"));
    Request->ProcessRequest();
}

/*Assigned function on successfull http call*/
void AHttpActor::OnResponseReceived(FHttpRequestPtr Request, FHttpResponsePtr Response, bool bWasSuccessful)
{

    //Create a pointer to hold the json serialized data
    TSharedPtr JsonObject;
    
    //Create a reader pointer to read the json data
    TSharedRef Reader = TJsonReaderFactory::Create(Response->GetContentAsString());
    
    //Deserialize the json data given Reader and the actual object to deserialize
    if (FJsonSerializer::Deserialize(Reader, JsonObject))
    {
        //Get the value of the json object by field name
        int32 recievedInt = JsonObject->GetIntegerField("customInt");

        //Output it to the engine
        GEngine->AddOnScreenDebugMessage(1, 2.0f, FColor::Green, FString::FromInt(recievedInt));
    }
}

That's it. For the code. Save and compile the files via Visual Studio -> Build -> [ProjectName] Build. Or inside of UE4's hot reaload tools.

PHP code

But that's not all now we need to create a PHP script to return some data.

Assuming you found the location of your htdocs and where you will put your php script, the code is:

 5);

    //Set the headers
    header('Content-Type: application/json');

    //Encode the variable, and save the encoded string
    $encoded = json_encode($theVar);

    //Output it
    echo $encoded;
?>

That's it now. When you start the game a 5 should be outputted to the screen, or whatever number you typed. in array('customInt' => N); N is the number.

Conclusion

From now on, you can create an advanced system of that and use it in your game!

Thanks for reading this tutorial.