How to make an HTTP Request from Unreal

Something like that :slight_smile: I don’t know what level of answer you’re expecting so if the code below is too complicated then just tell me and I’ll explain what it does.



void YourClass::YourFunction()
{
        TSharedPtr<FJsonObject> JsonObject = MakeShareable(new FJsonObject());

        JsonObject->SetStringField(TEXT("some_string_field"), *FString::Printf(TEXT("%s"), *SomeFStringVariable));

        FString OutputString;

        TSharedRef<TJsonWriter<TCHAR>> JsonWriter = TJsonWriterFactory<>::Create(&OutputString);

        FJsonSerializer::Serialize(JsonObject.ToSharedRef(), JsonWriter);

        TSharedRef<IHttpRequest> HttpRequest = FHttpModule::Get().CreateRequest();

        HttpRequest->SetVerb("POST");

        HttpRequest->SetHeader("Content-Type", "application/json");

        HttpRequest->SetURL(*FString::Printf(TEXT("%s"), *UrlAddressAsString));

        HttpRequest->SetContentAsString(OutputString);

        HttpRequest->OnProcessRequestComplete().BindUObject(this, &YourClass::OnYourFunctionCompleted);

        HttpRequest->ProcessRequest();
}

void YourClass::OnYourFunctionCompleted(FHttpRequestPtr Request, FHttpResponsePtr Response, bool bWasSuccessful)
{
    if (bWasSuccessful && Response->GetContentType() == "application/json")
    {
        TSharedPtr<FJsonObject> JsonObject = MakeShareable(new FJsonObject());

        TSharedRef<TJsonReader<TCHAR>> JsonReader =  TJsonReaderFactory<TCHAR>::Create(Response->GetContentAsString());

        FJsonSerializer::Deserialize(JsonReader, JsonObject);

        SomeOtherVariable = JsonObject->GetStringField("some_response_field");

    }
    else
    {
        // Handle error here
    }
}


7 Likes