http訪問工具類
unity 原來有個http訪問的工具類WWW,參考http://www.superzhan.cn/?p=112。在新版本的Unity中,推出了新的工具類UnityWebRequest,可以代替原來的WWW類。
簡單的Get訪問
UnityWebRequest包含多個靜態方法,可以創建一個UnityWebRequest對象,調用SendWebRequest正式發送請求。在協程返回結果后,需要判斷是否有錯誤,再做處理。
using System.Collections;
using System.Collections.Generic;
using System.Net;
using UnityEngine;
using UnityEngine.Networking;
public class NewBehaviourScript : MonoBehaviour
{
void Start()
{
StartCoroutine(GetRequest());
}
public IEnumerator GetRequest()
{
string url = "https://www.baidu.com/";
using (UnityWebRequest webRequest = UnityWebRequest.Get(url))
{
yield return webRequest.SendWebRequest();
if (webRequest.isHttpError || webRequest.isNetworkError)
{
Debug.LogError(webRequest.error + "\n" + webRequest.downloadHandler.text);
}
else
{
Debug.Log(webRequest.downloadHandler.text);
}
}
}
}
Http post訪問
項目中post訪問提交的數據都是json格式的,這里需要對提交的數據uploadHandler做處理,把提交的數據抓換為byte數組。 如果提交的是form表單,可以參考官方文檔。
public IEnumerator PostRequest(string methodName, string jsonString, Action<string> callback)
{
string url = baseUrl + methodName;
using (UnityWebRequest webRequest = new UnityWebRequest(url, "POST"))
{
byte[] bodyRaw = Encoding.UTF8.GetBytes(jsonString);
webRequest.uploadHandler = (UploadHandler) new UploadHandlerRaw(bodyRaw);
webRequest.downloadHandler = (DownloadHandler) new DownloadHandlerBuffer();
yield return webRequest.SendWebRequest();
if (webRequest.isHttpError || webRequest.isNetworkError)
{
Debug.LogError(webRequest.error + "\n" + webRequest.downloadHandler.text);
if (callback != null)
{
callback(null);
}
}
else
{
if (callback != null)
{
callback(webRequest.downloadHandler.text);
}
}
}
}
http header設置
訪問http接口時,考慮到安全方面的問題,可以在提交的數據里面加上一個key字符串,用於身份驗證。
這個key字符串可以放到http 的 header中。
設置header方法
webRequest.SetRequestHeader(Key, Value);
完整工具代碼封裝
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using UnityEngine.Networking;
using System.Text;
/// <summary>
/// Http Request SDK
/// </summary>
public class HttpTool : MonoBehaviour
{
private static HttpTool _instacne = null;
public string baseUrl = "https://127.0.0.1:3000/";
public string sKey = "zoo_visit_key";
Dictionary<string, string> requestHeader = new Dictionary<string, string>(); // header
public static HttpTool Instance
{
get
{
if (_instacne == null)
{
Debug.LogError("Awake error");
}
return _instacne;
}
}
void Awake()
{
DontDestroyOnLoad(gameObject);
HttpTool._instacne = gameObject.GetComponent<HttpTool>();
//http header 的內容
requestHeader.Add("Content-Type", "application/json");
requestHeader.Add("sKey", sKey);
}
public void Get(string methodName, Action<string> callback)
{
StartCoroutine(GetRequest(methodName, callback));
}
public IEnumerator GetRequest(string methodName, Action<string> callback)
{
string url = baseUrl + methodName;
using (UnityWebRequest webRequest = UnityWebRequest.Get(url))
{
//設置header
foreach (var v in requestHeader)
{
webRequest.SetRequestHeader(v.Key, v.Value);
}
yield return webRequest.SendWebRequest();
if (webRequest.isHttpError || webRequest.isNetworkError)
{
Debug.LogError(webRequest.error + "\n" + webRequest.downloadHandler.text);
if (callback != null)
{
callback(null);
}
}
else
{
if (callback != null)
{
callback(webRequest.downloadHandler.text);
}
}
}
}
//jsonString 為json字符串,post提交的數據包為json
public void Post(string methodName,string jsonString, Action<string> callback)
{
StartCoroutine(PostRequest(methodName,jsonString,callback));
}
public IEnumerator PostRequest(string methodName, string jsonString, Action<string> callback)
{
string url = baseUrl + methodName;
// Debug.Log(string.Format("url:{0} postData:{1}",url,jsonString));
using (UnityWebRequest webRequest = new UnityWebRequest(url, "POST"))
{
byte[] bodyRaw = Encoding.UTF8.GetBytes(jsonString);
webRequest.uploadHandler = (UploadHandler) new UploadHandlerRaw(bodyRaw);
webRequest.downloadHandler = (DownloadHandler) new DownloadHandlerBuffer();
foreach (var v in requestHeader)
{
webRequest.SetRequestHeader(v.Key, v.Value);
}
yield return webRequest.SendWebRequest();
if (webRequest.isHttpError || webRequest.isNetworkError)
{
Debug.LogError(webRequest.error + "\n" + webRequest.downloadHandler.text);
if (callback != null)
{
callback(null);
}
}
else
{
if (callback != null)
{
callback(webRequest.downloadHandler.text);
}
}
}
}
}
參考
更多的使用方法,可以參考官方文檔。
https://docs.unity3d.com/2019.1/Documentation/ScriptReference/Networking.UnityWebRequest.html