SIOJRequestJSON.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  1. // Modifications Copyright 2018-current Getnamo. All Rights Reserved
  2. // Copyright 2014 Vladimir Alyamkin. All Rights Reserved.
  3. #include "SIOJRequestJSON.h"
  4. #include "ISIOJson.h"
  5. #include "SIOJLibrary.h"
  6. #include "SIOJsonValue.h"
  7. #include "SIOJsonObject.h"
  8. template <class T> void FSIOJLatentAction<T>::Cancel()
  9. {
  10. UObject *Obj = Request.Get();
  11. if (Obj != nullptr)
  12. {
  13. ((USIOJRequestJSON*)Obj)->Cancel();
  14. }
  15. }
  16. USIOJRequestJSON::USIOJRequestJSON(const class FObjectInitializer& PCIP)
  17. : Super(PCIP),
  18. BinaryContentType(TEXT("application/octet-stream"))
  19. {
  20. RequestVerb = ESIORequestVerb::GET;
  21. RequestContentType = ESIORequestContentType::x_www_form_urlencoded_url;
  22. bShouldHaveBinaryResponse = false;
  23. OnProcessURLCompleteCallback = nullptr;
  24. ResetData();
  25. }
  26. USIOJRequestJSON* USIOJRequestJSON::ConstructRequest(UObject* WorldContextObject)
  27. {
  28. return NewObject<USIOJRequestJSON>();
  29. }
  30. USIOJRequestJSON* USIOJRequestJSON::ConstructRequestExt(
  31. UObject* WorldContextObject,
  32. ESIORequestVerb Verb,
  33. ESIORequestContentType ContentType)
  34. {
  35. USIOJRequestJSON* Request = ConstructRequest(WorldContextObject);
  36. Request->SetVerb(Verb);
  37. Request->SetContentType(ContentType);
  38. return Request;
  39. }
  40. void USIOJRequestJSON::SetVerb(ESIORequestVerb Verb)
  41. {
  42. RequestVerb = Verb;
  43. }
  44. void USIOJRequestJSON::SetCustomVerb(FString Verb)
  45. {
  46. CustomVerb = Verb;
  47. }
  48. void USIOJRequestJSON::SetContentType(ESIORequestContentType ContentType)
  49. {
  50. RequestContentType = ContentType;
  51. }
  52. void USIOJRequestJSON::SetBinaryContentType(const FString &ContentType)
  53. {
  54. BinaryContentType = ContentType;
  55. }
  56. void USIOJRequestJSON::SetBinaryRequestContent(const TArray<uint8> &Bytes)
  57. {
  58. RequestBytes = Bytes;
  59. }
  60. void USIOJRequestJSON::SetHeader(const FString& HeaderName, const FString& HeaderValue)
  61. {
  62. RequestHeaders.Add(HeaderName, HeaderValue);
  63. }
  64. //////////////////////////////////////////////////////////////////////////
  65. // Destruction and reset
  66. void USIOJRequestJSON::ResetData()
  67. {
  68. ResetRequestData();
  69. ResetResponseData();
  70. }
  71. void USIOJRequestJSON::ResetRequestData()
  72. {
  73. if (RequestJsonObj != nullptr)
  74. {
  75. RequestJsonObj->Reset();
  76. }
  77. else
  78. {
  79. RequestJsonObj = NewObject<USIOJsonObject>();
  80. }
  81. HttpRequest = FHttpModule::Get().CreateRequest();
  82. }
  83. void USIOJRequestJSON::ResetResponseData()
  84. {
  85. if (ResponseJsonObj != nullptr)
  86. {
  87. ResponseJsonObj->Reset();
  88. }
  89. else
  90. {
  91. ResponseJsonObj = NewObject<USIOJsonObject>();
  92. }
  93. ResponseHeaders.Empty();
  94. ResponseCode = -1;
  95. bIsValidJsonResponse = false;
  96. }
  97. void USIOJRequestJSON::Cancel()
  98. {
  99. ContinueAction = nullptr;
  100. ResetResponseData();
  101. }
  102. //////////////////////////////////////////////////////////////////////////
  103. // JSON data accessors
  104. USIOJsonObject* USIOJRequestJSON::GetRequestObject()
  105. {
  106. return RequestJsonObj;
  107. }
  108. void USIOJRequestJSON::SetRequestObject(USIOJsonObject* JsonObject)
  109. {
  110. RequestJsonObj = JsonObject;
  111. }
  112. USIOJsonObject* USIOJRequestJSON::GetResponseObject()
  113. {
  114. return ResponseJsonObj;
  115. }
  116. void USIOJRequestJSON::SetResponseObject(USIOJsonObject* JsonObject)
  117. {
  118. ResponseJsonObj = JsonObject;
  119. }
  120. ///////////////////////////////////////////////////////////////////////////
  121. // Response data access
  122. FString USIOJRequestJSON::GetURL()
  123. {
  124. return HttpRequest->GetURL();
  125. }
  126. ESIORequestStatus USIOJRequestJSON::GetStatus()
  127. {
  128. return ESIORequestStatus((uint8)HttpRequest->GetStatus());
  129. }
  130. int32 USIOJRequestJSON::GetResponseCode()
  131. {
  132. return ResponseCode;
  133. }
  134. FString USIOJRequestJSON::GetResponseHeader(const FString HeaderName)
  135. {
  136. FString Result;
  137. FString* Header = ResponseHeaders.Find(HeaderName);
  138. if (Header != nullptr)
  139. {
  140. Result = *Header;
  141. }
  142. return Result;
  143. }
  144. TArray<FString> USIOJRequestJSON::GetAllResponseHeaders()
  145. {
  146. TArray<FString> Result;
  147. for (TMap<FString, FString>::TConstIterator It(ResponseHeaders); It; ++It)
  148. {
  149. Result.Add(It.Key() + TEXT(": ") + It.Value());
  150. }
  151. return Result;
  152. }
  153. //////////////////////////////////////////////////////////////////////////
  154. // URL processing
  155. void USIOJRequestJSON::ProcessURL(const FString& Url)
  156. {
  157. HttpRequest->SetURL(Url);
  158. ProcessRequest();
  159. }
  160. void USIOJRequestJSON::ApplyURL(const FString& Url, USIOJsonObject *&Result, UObject* WorldContextObject, FLatentActionInfo LatentInfo)
  161. {
  162. HttpRequest->SetURL(Url);
  163. // Prepare latent action
  164. if (UWorld* World = GEngine->GetWorldFromContextObject(WorldContextObject, EGetWorldErrorMode::LogAndReturnNull))
  165. {
  166. FLatentActionManager& LatentActionManager = World->GetLatentActionManager();
  167. FSIOJLatentAction<USIOJsonObject*> *Kont = LatentActionManager.FindExistingAction<FSIOJLatentAction<USIOJsonObject*>>(LatentInfo.CallbackTarget, LatentInfo.UUID);
  168. if (Kont != nullptr)
  169. {
  170. Kont->Cancel();
  171. LatentActionManager.RemoveActionsForObject(LatentInfo.CallbackTarget);
  172. }
  173. LatentActionManager.AddNewAction(LatentInfo.CallbackTarget, LatentInfo.UUID, ContinueAction = new FSIOJLatentAction<USIOJsonObject*>(this, Result, LatentInfo));
  174. }
  175. ProcessRequest();
  176. }
  177. void USIOJRequestJSON::ProcessRequest()
  178. {
  179. // Set verb
  180. switch (RequestVerb)
  181. {
  182. case ESIORequestVerb::GET:
  183. HttpRequest->SetVerb(TEXT("GET"));
  184. break;
  185. case ESIORequestVerb::POST:
  186. HttpRequest->SetVerb(TEXT("POST"));
  187. break;
  188. case ESIORequestVerb::PUT:
  189. HttpRequest->SetVerb(TEXT("PUT"));
  190. break;
  191. case ESIORequestVerb::DEL:
  192. HttpRequest->SetVerb(TEXT("DELETE"));
  193. break;
  194. case ESIORequestVerb::CUSTOM:
  195. HttpRequest->SetVerb(CustomVerb);
  196. break;
  197. default:
  198. break;
  199. }
  200. // Set content-type
  201. switch (RequestContentType)
  202. {
  203. case ESIORequestContentType::x_www_form_urlencoded_url:
  204. {
  205. HttpRequest->SetHeader(TEXT("Content-Type"), TEXT("application/x-www-form-urlencoded"));
  206. FString UrlParams = "";
  207. uint16 ParamIdx = 0;
  208. // Loop through all the values and prepare additional url part
  209. for (auto RequestIt = RequestJsonObj->GetRootObject()->Values.CreateIterator(); RequestIt; ++RequestIt)
  210. {
  211. FString Key = RequestIt.Key();
  212. FString Value = RequestIt.Value().Get()->AsString();
  213. if (!Key.IsEmpty() && !Value.IsEmpty())
  214. {
  215. UrlParams += ParamIdx == 0 ? "?" : "&";
  216. UrlParams += USIOJLibrary::PercentEncode(Key) + "=" + USIOJLibrary::PercentEncode(Value);
  217. }
  218. ParamIdx++;
  219. }
  220. // Apply params
  221. HttpRequest->SetURL(HttpRequest->GetURL() + UrlParams);
  222. UE_LOG(LogSIOJ, Log, TEXT("Request (urlencoded): %s %s %s"), *HttpRequest->GetVerb(), *HttpRequest->GetURL(), *UrlParams);
  223. break;
  224. }
  225. case ESIORequestContentType::x_www_form_urlencoded_body:
  226. {
  227. HttpRequest->SetHeader(TEXT("Content-Type"), TEXT("application/x-www-form-urlencoded"));
  228. FString UrlParams = "";
  229. uint16 ParamIdx = 0;
  230. // Loop through all the values and prepare additional url part
  231. for (auto RequestIt = RequestJsonObj->GetRootObject()->Values.CreateIterator(); RequestIt; ++RequestIt)
  232. {
  233. FString Key = RequestIt.Key();
  234. FString Value = RequestIt.Value().Get()->AsString();
  235. if (!Key.IsEmpty() && !Value.IsEmpty())
  236. {
  237. UrlParams += ParamIdx == 0 ? "" : "&";
  238. UrlParams += USIOJLibrary::PercentEncode(Key) + "=" + USIOJLibrary::PercentEncode(Value);
  239. }
  240. ParamIdx++;
  241. }
  242. // Apply params
  243. HttpRequest->SetContentAsString(UrlParams);
  244. UE_LOG(LogSIOJ, Log, TEXT("Request (url body): %s %s %s"), *HttpRequest->GetVerb(), *HttpRequest->GetURL(), *UrlParams);
  245. break;
  246. }
  247. case ESIORequestContentType::binary:
  248. {
  249. HttpRequest->SetHeader(TEXT("Content-Type"), BinaryContentType);
  250. HttpRequest->SetContent(RequestBytes);
  251. UE_LOG(LogSIOJ, Log, TEXT("Request (binary): %s %s"), *HttpRequest->GetVerb(), *HttpRequest->GetURL());
  252. break;
  253. }
  254. case ESIORequestContentType::json:
  255. {
  256. HttpRequest->SetHeader(TEXT("Content-Type"), TEXT("application/json"));
  257. // Serialize data to json string
  258. FString OutputString;
  259. TSharedRef< TJsonWriter<> > Writer = TJsonWriterFactory<>::Create(&OutputString);
  260. FJsonSerializer::Serialize(RequestJsonObj->GetRootObject().ToSharedRef(), Writer);
  261. // Set Json content
  262. HttpRequest->SetContentAsString(OutputString);
  263. UE_LOG(LogSIOJ, Log, TEXT("Request (json): %s %s %s"), *HttpRequest->GetVerb(), *HttpRequest->GetURL(), *OutputString);
  264. break;
  265. }
  266. default:
  267. break;
  268. }
  269. // Apply additional headers
  270. for (TMap<FString, FString>::TConstIterator It(RequestHeaders); It; ++It)
  271. {
  272. HttpRequest->SetHeader(It.Key(), It.Value());
  273. }
  274. // Bind event
  275. if (bShouldHaveBinaryResponse)
  276. {
  277. HttpRequest->OnProcessRequestComplete().BindUObject(this, &USIOJRequestJSON::OnProcessRequestCompleteBinaryResult);
  278. }
  279. else
  280. {
  281. HttpRequest->OnProcessRequestComplete().BindUObject(this, &USIOJRequestJSON::OnProcessRequestComplete);
  282. }
  283. // Execute the request
  284. HttpRequest->ProcessRequest();
  285. }
  286. //////////////////////////////////////////////////////////////////////////
  287. // Request callbacks
  288. void USIOJRequestJSON::OnProcessRequestComplete(FHttpRequestPtr Request, FHttpResponsePtr Response, bool bWasSuccessful)
  289. {
  290. // Be sure that we have no data from previous response
  291. ResetResponseData();
  292. // Check we have a response and save response code as int32
  293. if(Response.IsValid())
  294. {
  295. ResponseCode = Response->GetResponseCode();
  296. }
  297. // Check we have result to process futher
  298. if (!bWasSuccessful || !Response.IsValid())
  299. {
  300. UE_LOG(LogSIOJ, Error, TEXT("Request failed (%d): %s"), ResponseCode, *Request->GetURL());
  301. // Broadcast the result event
  302. OnRequestFail.Broadcast(this);
  303. OnStaticRequestFail.Broadcast(this);
  304. return;
  305. }
  306. // Save response data as a string
  307. ResponseContent = Response->GetContentAsString();
  308. // Log response state
  309. UE_LOG(LogSIOJ, Log, TEXT("Response (%d): %s"), ResponseCode, *ResponseContent);
  310. // Process response headers
  311. TArray<FString> Headers = Response->GetAllHeaders();
  312. for (FString Header : Headers)
  313. {
  314. FString Key;
  315. FString Value;
  316. if (Header.Split(TEXT(": "), &Key, &Value))
  317. {
  318. ResponseHeaders.Add(Key, Value);
  319. }
  320. }
  321. // Try to deserialize data to JSON
  322. TSharedRef<TJsonReader<TCHAR>> JsonReader = TJsonReaderFactory<TCHAR>::Create(ResponseContent);
  323. FJsonSerializer::Deserialize(JsonReader, ResponseJsonObj->GetRootObject());
  324. // Decide whether the request was successful
  325. bIsValidJsonResponse = bWasSuccessful && ResponseJsonObj->GetRootObject().IsValid();
  326. // Log errors
  327. if (!bIsValidJsonResponse)
  328. {
  329. if (!ResponseJsonObj->GetRootObject().IsValid())
  330. {
  331. // As we assume it's recommended way to use current class, but not the only one,
  332. // it will be the warning instead of error
  333. UE_LOG(LogSIOJ, Warning, TEXT("JSON could not be decoded!"));
  334. }
  335. }
  336. // Broadcast the result event
  337. OnRequestComplete.Broadcast(this);
  338. OnStaticRequestComplete.Broadcast(this);
  339. // Finish the latent action
  340. if (ContinueAction)
  341. {
  342. FSIOJLatentAction<USIOJsonObject*> *K = ContinueAction;
  343. ContinueAction = nullptr;
  344. K->Call(ResponseJsonObj);
  345. }
  346. }
  347. void USIOJRequestJSON::OnProcessRequestCompleteBinaryResult(FHttpRequestPtr Request, FHttpResponsePtr Response, bool bWasSuccessful)
  348. {
  349. // Be sure that we have no data from previous response
  350. ResetResponseData();
  351. // Check we have a response and save response code as int32
  352. if (Response.IsValid())
  353. {
  354. ResponseCode = Response->GetResponseCode();
  355. }
  356. // Check we have result to process futher
  357. if (!bWasSuccessful || !Response.IsValid())
  358. {
  359. UE_LOG(LogSIOJ, Error, TEXT("Request failed (%d): %s"), ResponseCode, *Request->GetURL());
  360. // Broadcast the result event
  361. OnRequestFail.Broadcast(this);
  362. OnStaticRequestFail.Broadcast(this);
  363. return;
  364. }
  365. ResultBinaryData = Response->GetContent();
  366. // Broadcast the result event
  367. OnRequestComplete.Broadcast(this);
  368. OnStaticRequestComplete.Broadcast(this);
  369. if (OnProcessURLCompleteCallback)
  370. {
  371. OnProcessURLCompleteCallback(ResultBinaryData);
  372. }
  373. }
  374. //////////////////////////////////////////////////////////////////////////
  375. // Tags
  376. void USIOJRequestJSON::AddTag(FName Tag)
  377. {
  378. if (Tag != NAME_None)
  379. {
  380. Tags.AddUnique(Tag);
  381. }
  382. }
  383. int32 USIOJRequestJSON::RemoveTag(FName Tag)
  384. {
  385. return Tags.Remove(Tag);
  386. }
  387. bool USIOJRequestJSON::HasTag(FName Tag) const
  388. {
  389. return (Tag != NAME_None) && Tags.Contains(Tag);
  390. }