Hello Guys.
I am implementing a request-response module for my game. I want to request to server for some data and then process the response received and use it in my game.
I know how to make a request and receive the response.
This the code I have:
USQLDBClass.h:
class ROBOREV_WIN_API USQLDBClass : public UObject
{
GENERATED_BODY()
public:
FString getMethod(FString method, TMapBase<FString, FString, true> argMap);
private:
void Request(FString requestURL, FString args);
void RequestComplete(FHttpRequestPtr Request, FHttpResponsePtr Response, bool bWasSuccessful);
bool responseStatus;
FString MessageBody;
};
USQLDBClass.cpp:
FString USQLDBClass::getMethod(FString method, TMapBase<FString, FString,true> argMap){
FString requestURL = "http://whatever.my.url.is.php";
FString args = "";
Request(requestURL, args);
if (responseStatus)
return MessageBody;
else
return "";
}
void USQLDBClass::Request(FString requestURL, FString args){
requestURL.Append(args);
TSharedRef <IHttpRequest> HttpRequest = FHttpModule::Get().CreateRequest();
HttpRequest->SetHeader(TEXT("Content-Type"), TEXT("application / json; charset = utf-8"));
HttpRequest->SetURL(requestURL);
HttpRequest->SetVerb(TEXT("POST"));
HttpRequest->OnProcessRequestComplete().BindUObject(this, &USQLDBClass::RequestComplete);
HttpRequest->ProcessRequest();
}
void USQLDBClass::RequestComplete(FHttpRequestPtr Request, FHttpResponsePtr Response, bool bWasSuccessful
MessageBody = "";
if (!Response.IsValid())
{
MessageBody = "{\" success \": \" Error: Unable to process HTTP Request ! \"}";
responseStatus = false;
return;
}
else if (EHttpResponseCodes::IsOk(Response->GetResponseCode()))
{
MessageBody = Response->GetContentAsString();
responseStatus = true;
}
else
{
MessageBody = FString::Printf(TEXT("{\" success \": \" HTTP Error:% d \"}"), Response->GetResponseCode());
responseStatus = false;
}
}
My problem is that I am expecting the HttpRequest to be processed instantly,i.e., in ‘getMethod’ function, once I make a call to the ‘Request’ function, I am hoping that the variable ‘responseStatus’ is set to true, and if it is set true I want to send the received response back.
But for some reason, the ‘HttpRequest’ is processed later. I mean, the ‘getMethod’ function is processed and then the control flow comes to the ‘RequestComplete’ function.
Is there a way to solve this? Make the getMethod function wait for the request to complete?