Greetings, i’m trying to Get some Json data in a local server, but i can’t, i tried some tutorials, my code is exatly the same of the tutorials but nothing happens.
Tutorials:
My actual code (same as examples basically) :
HttpActor.cpp
// Fill out your copyright notice in the Description page of Project Settings.
#include "HttpActor.h"
#include "Runtime/Online/HTTP/Public/Http.h"
#include "CPPProject.h"
#include "Engine.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<IHttpRequest> Request = Http->CreateRequest();
Request->OnProcessRequestComplete().BindUObject(this, &AHttpActor::OnResponseReceived);
//This is the url on which to process the request
Request->SetURL("http://localhost:8080/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<FJsonObject> JsonObject;
//Create a reader pointer to read the json data
TSharedRef<TJsonReader<>> 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(TEXT("customInt"));
//Output it to the engine
GEngine->AddOnScreenDebugMessage(1, 2.0f, FColor::Green, FString::FromInt(recievedInt));
}
}
Here is little example on how you create JSON data string:
FString data_to_send = ""; // This will the JSONData you will be sending
FString string_value = "Hello World";
int int_value = 10;
bool boolean_value = true;
TSharedPtr<FJsonObject> JsonObject = MakeShareable(new FJsonObject);
JsonObject->SetStringField("key1", string_value );
JsonObject->SetNumberField("key2", int_value );
JsonObject->SetBoolField("key3", boolean_value);
TSharedRef<TJsonWriter<>> json_writer = TJsonWriterFactory<>::Create(&data_to_send );
FJsonSerializer::Serialize(JsonObject.ToSharedRef(), json_writer);
// you can print our the data here to confirm it is write
Thank you ctalystnetwork for the answer, i’m studying the code to understand how you did.
But, i have another question, assuming i want to create a simple mmorpg, is Json the best way to connect my game to database? or i can use a simple TCP/UDP to do it?