UE4与WEB服务器交互(json)

来源:互联网 发布:海岛奇兵雕像数据 编辑:程序博客网 时间:2024/05/16 15:19

概述

制作游戏在很多情况下需要和WEB服务器进行交互,最常见的是在做Demo时需要通过游戏向WEB服务器传递数据(登录/注册验请求),WEB服务器处理(操作数据库)之后返回结果并调用指定的方法。 该教程简单介绍了如何通过UE4向WEB服务器(PHP)发送json数据包及回调方法。

添加模块和头文件引用
在代码编辑器中打开项目解决方案,在<Solution Name>/Source/<ProjectName>路径下,找到并打开<ProjectName>.Build.cs文件,添加HTTP模块:
[C++] 纯文本查看 复制代码
1PrivateDependencyModuleNames.AddRange(new string[] {"HTTP"});
2PrivateIncludePathModuleNames.AddRange(new string[] {"HTTP"});

然后在需要实现该功能的类文件中添加如下的头文件引用:
[C++] 纯文本查看 复制代码
1#include "Http.h"
2#include "Json.h"

创建json数据包
数据内容为:
[C++] 纯文本查看 复制代码
1"user" "StormUnited"}

创建:
[C++] 纯文本查看 复制代码
1// Create a writer and hold it in this FString
2FString JsonStr;
3TSharedRef< TJsonWriter<TCHAR, TCondensedJsonPrintPolicy<TCHAR> > > JsonWriter = TJsonWriterFactory<TCHAR, TCondensedJsonPrintPolicy<TCHAR> >::Create(&JsonStr);
4JsonWriter->WriteObjectStart();
5JsonWriter->WriteValue(TEXT("user"), TEXT("StormUnited"));
6JsonWriter->WriteObjectEnd();
7  
8// Close the writer and finalize the output such that JsonStr has what we want
9JsonWriter->Close();

至此,json数据包准备完成。

准备接收json数据包的PHP网页
本示例中使用了PHP,你可以选择使用搭建动态网站或者服务器的开源软件,比如说wamp/lamp等在本机上建立一个WEB服务器来解析PHP页面。 创建mywebpage.php文件,并添加如下代码:
[PHP] 纯文本查看 复制代码
1<?php
2     // 首先接收上传的数据
3     $post_data file_get_contents('php://input');
4     // 解析json字符串
5     $obj = json_decode($post_data);
6     // 获取包含在Json字符串中的数据
7     echo $obj->{'user'};
8?>

POST数据
将通过如下的代码将上面准备好的json数据包提交给 http://localhost/mywebpage.php
  • SetHeader:可以设置POST数据的格式
  • SetURL:可以指定用于处理上传数据的链接
  • SetVerb:可以设置POST/PUT/GET
  • SetContentAsString:用于填充上传的数据内容
  • OnProcessRequestComplete().BindUObject 用于指定在发送请求之后的回调方法。

[C++] 纯文本查看 复制代码
1TSharedRef<IHttpRequest> HttpRequest = FHttpModule::Get().CreateRequest();
2HttpRequest->SetHeader(TEXT("Content-Type"), TEXT("application/json; charset=utf-8"));
3HttpRequest->SetURL(TEXT("http://localhost/mywebpage.php"));
4HttpRequest->SetVerb(TEXT("POST"));
5HttpRequest->SetContentAsString(JsonStr);
6HttpRequest->OnProcessRequestComplete().BindUObject(this, &ASUMiniGameMode::HttpCompleteCallback);
7HttpRequest->ProcessRequest();


关于回调函数的结构:void HttpCompleteCallback(FHttpRequestPtr Request, FHttpResponsePtr Response, bool bWasSuccessful); 示例:
[C++] 纯文本查看 复制代码
01void ASUMiniGameMode::HttpCompleteCallback(FHttpRequestPtr Request, FHttpResponsePtr Response,bool bWasSuccessful)
02{
03     FString MessageBody = "";
04  
05     // If HTTP fails client-side, this will still be called but with a NULL shared pointer!
06     if (!Response.IsValid())
07     {
08          MessageBody = "{\"success\":\"Error: Unable to process HTTP Request!\"}";
09     }
10     else if (EHttpResponseCodes::IsOk(Response->GetResponseCode()))
11     {
12          MessageBody = Response->GetContentAsString();
13     }
14     else
15     {
16          MessageBody = FString::Printf(TEXT("{\"success\":\"HTTP Error: %d\"}"), Response->GetResponseCode());
17     }
18}


一旦发送出请求后肯定会调用HttpCompleteCallback方法,WEB服务器处理的数据结果包含在Response参数中,可以通过Response->GetContentAsString()来获取返回的字符串,比如在本例中是StormUnited。
总结
联系我:bm0nkey
常见问题及参考
  • https://answers.unrealengine.com/questions/4383/sending-an-fstring-via-sockets.html
  • https://answers.unrealengine.com/questions/4406/need-help-with-json-objects.html
  • https://answers.unrealengine.com/questions/2830/best-way-to-perform-a-http-request.html
  • https://answers.unrealengine.com/questions/3530/does-httprequest-use-httpmanager-by-default.html
  • https://answers.unrealengine.com/questions/2830/best-way-to-perform-a-http-request.html
  • https://answers.unrealengine.com/questions/23170/making-http-calls.html
  • https://answers.unrealengine.com/questions/31079/http%E9%80%9A%E4%BF%A1%E3%81%AB%E3%81%A4%E3%81%84%E3%81%A6.html
  • https://answers.unrealengine.com/questions/26704/trouble-deserializing-json.html
  • https://answers.unrealengine.com/questions/2830/best-way-to-perform-a-http-request.html
0 0