UnityWebRequest HTTP 请求服务
所用到插件
LitJson链接:
链接:https://pan.baidu.com/s/1lEbQbAQNewaxs-CKahpBcA
提取码:ovt9
请求服务
using UnityEngine;
using System;
using LitJson ;
using System.Text.RegularExpressions;
/// <summary>
/// 请求服务
/// </summary>
public class RequestServer : ServerManager
{
/// <summary> 登录验证 </summary>
/// <param name="action">回调函数</param>
/// <param name="accountNumber">账号</param>
/// <param name="password">密码</param>
public void LoginVerification(Action<string> action, string accountNumber, string password)
{
Debug.Log("登录验证");
//============JSON的生成 使用的LitJson============================
JsonData data = new JsonData();
//生成嵌套结构的json
data["telphone"] = accountNumber;
data["password"] = password;
string json = data.ToJson();
//避免乱码
Regex reg = new Regex(@"(?i)\\[uU]([0-9a-f]{4})");
json = reg.Replace(json, delegate (Match m) { return ((char)Convert.ToInt32(m.Groups[1].Value, 16)).ToString(); });
Debug.Log(json);
//url接口
string url = ConfigManager.projectInforDataConfig.ConfigData.mServiceUrl + "customer/login";
StartCoroutine(ServerPostUrl(url, json, action));
}
}
服务器管理器
token 功能没有测试过
using System;
using System.Collections;
using System.Collections.Specialized;
using System.Net;
using System.Reflection;
using UnityEngine;
using UnityEngine.Networking;
public class ServerManager : MonoBehaviour {
/// <summary> 数据库请求 </summary>
/// <param name="url">接口地址</param>
/// <param name="postData">请求数据</param>
/// <param name="action">执行回调方法</param>
/// <returns></returns>
protected IEnumerator ServerPostUrl(string url, string postData, Action<string> action, string token = "")
{
Debug.Log("Url : " + url);
using (UnityWebRequest www = new UnityWebRequest(url, "POST"))
{
if (token != "")
{
var property = typeof(WebHeaderCollection).GetProperty("InnerCollection", BindingFlags.Instance | BindingFlags.NonPublic);
if (property != null)
{
var collection = property.GetValue(www.GetResponseHeaders(), null) as NameValueCollection;
collection[name] = token;
}
}
byte[] postBytes = System.Text.Encoding.UTF8.GetBytes(postData);
www.uploadHandler = (UploadHandler)new UploadHandlerRaw(postBytes);
www.SetRequestHeader("Content-Type", "application/json;charset=utf-8");
www.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();
www.timeout = 30;
yield return www.SendWebRequest();
Debug.Log("ReponseCode : " + www.responseCode + "\nError : " + www.error);
if (www.isHttpError || www.isNetworkError)
{
Debug.LogWarning("Error: " +www.error + "\n" + www.downloadHandler.text);
}
else
{
if (www.responseCode == 200)
{
string text = www.downloadHandler.text;
Debug.Log(url + "\n" + text);
action(text);
}
else
{
if (www.responseCode == 404)
{
Debug.LogWarning("Error : " + 404);
}
if (www.responseCode == 500)
{
Debug.LogWarning("Error : " + 500);
}
}
}
}
}
}