587
社区成员
![](https://csdnimg.cn/release/cmsfe/public/img/topic.427195d5.png)
![](https://csdnimg.cn/release/cmsfe/public/img/me.40a70ab0.png)
![](https://csdnimg.cn/release/cmsfe/public/img/task.87b52881.png)
![](https://csdnimg.cn/release/cmsfe/public/img/share-circle.3e0b7822.png)
更简单的在Unity中使用Http方法。
用来更为优雅的实现对网络请求以及对后端数据的处理。
需要通过http方法从网络上请求数据时会用到。
方便代码编写,是代码更为易懂,更为简洁。
cookie的设置,类本身的设计,以及对于易用性的考虑。
基本思路就是将向协程中传入地址、序列化好的body以及处理响应结果的action。
对于登陆的问题,由于我自己测试时后端返回的setcookie无法生效,所以需要对登录token进行单独的获取。
public static IEnumerator PostWithHeader(string url, string content, Action action = null, string contentType = "application/json;charset=utf-8")
{
Debug.Log("GetWithHeader" + "<color=darkblue>" + content);
UnityWebRequest www = UnityWebRequest.Post(url, content);
byte[] bodyRaw = Encoding.UTF8.GetBytes(content);
www.uploadHandler = new UploadHandlerRaw(bodyRaw);
www.SetRequestHeader("Cookie", loginToken);
www.SetRequestHeader("Content-Type", contentType);
yield return www.SendWebRequest();
if (www.result != UnityWebRequest.Result.Success)
{
Debug.Log("Post on" + url + "Error" + www.responseCode);
}
else
{
Debug.Log("Post on" + url + "finished");
#if UNITY_EDITOR
Debug.Log(www.downloadHandler.text);
#endif
//T value = JsonConvert.DeserializeObject<Response<T>>(www.downloadHandler.text).data;
action?.Invoke();
}
}
class Response<T>
{
public int code { get; set; }
public string msg { get; set; }
public T data { get; set; }
}
public IEnumerator LoginRequest(string url, string content, Action<string> messageHandler = null, string contentType = "application/json;charset=utf-8")
{
UnityWebRequest www = UnityWebRequest.Post(url, content);
byte[] bodyRaw = Encoding.UTF8.GetBytes(content);
www.uploadHandler = new UploadHandlerRaw(bodyRaw);
www.SetRequestHeader("Content-Type", contentType);
yield return www.SendWebRequest();
if (www.result != UnityWebRequest.Result.Success)
{
Debug.Log("Poston " + url + " Error " + www.responseCode);
}
else
{
Debug.Log("<color=green>Poston " + url + " finished");
#if UNITY_EDITOR
Debug.Log(www.downloadHandler.text);
#endif
string setCookie = www.GetResponseHeader("Set-Cookie");
Debug.Log(setCookie.Substring(0,setCookie.IndexOf(";")));
string value = JsonConvert.DeserializeObject<Response<UserResponse>>(www.downloadHandler.text).msg;
GlobalData.userInfo = JsonConvert.DeserializeObject<Response<UserResponse>>(www.downloadHandler.text).data.user;
Debug.Log(GlobalData.userInfo.name);
if (value == "登录成功")
{
WebBase.loginToken = setCookie.Substring(0, setCookie.IndexOf(";"));
eventCenter.EventTrigger<Action>("DialogAction", ActionToHomeScene);
}
messageHandler?.Invoke(value);
}
}
由于本次项目功能特别多,所以需要在封装上多下一点功夫,不然庞大的代码我自己找起来都有些麻烦,于是就诞生了这个封装。我认为在今后的学习中还是要多多编写这样的功能组件,丰富自己的代码库。