using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using UnityEngine;
using UnityEngine.Networking;
public class HttpNetMgr
{
public enum MethodType
{
GET,
POST
}
public class DownloadHanlderType
{
public const string kHttpBYTE = "BYTE";
public const string kHttpTEXT = "TEXT";
}
public static IEnumerator HTTPRequest(string url, Dictionary<string, object> param, MethodType methodType, Action<object> callback, string dateType = "TEXT")
{
UnityWebRequest request = null;
Debug.Log("OKOKOK");
switch (methodType)
{
case MethodType.GET: request = UnityWebRequest.Get(HttpNetMgr.CreateGetData(url, param)); break;
case MethodType.POST: request = UnityWebRequest.Post(url, HttpNetMgr.CreatePostData(param)); break;
}
request.SetRequestHeader("Content-Type", "application/x-www-form-urlencoded");//加入header
yield return request.SendWebRequest();
if (request.isHttpError || request.isNetworkError)
{
Debug.LogErrorFormat("Request Error: {0}", request.error);
}
if (request.isDone)
{
if (dateType == DownloadHanlderType.kHttpTEXT)
{
callback?.Invoke(request.downloadHandler.text);
}
else if (dateType == DownloadHanlderType.kHttpBYTE)
{
callback?.Invoke(request.downloadHandler.data);
}
}
}
private static string CreateGetData(string url, Dictionary<string, object> form)
{
string data = "";
if (form != null && form.Count > 0)
{
foreach (var item in form)
{
data += item.Key + "=";
data += item.Value.ToString() + "&";
}
}
if (url.IndexOf("?") == -1)
url += "?";
else
url += "&";
url += data.TrimEnd(new char[] { ‘&‘ });
return url;
}
private static WWWForm CreatePostData(Dictionary<string, object> formData)
{
WWWForm form = new WWWForm();
if (formData != null && formData.Count > 0)
{
foreach (var item in formData)
{
if (item.Value is byte[])
form.AddBinaryData(item.Key, item.Value as byte[]);
else
form.AddField(item.Key, item.Value.ToString());
}
}
return form;
}
}
void Start()
{
Debug.Log("START!!!!!!");
Dictionary<string, object> param = new Dictionary<string, object> {
{ "p1","Pa"} , { "p2", "Pb"}
};
StartCoroutine(
HttpNetMgr.HTTPRequest("http://127.0.0.1:8980/test", param, HttpNetMgr.MethodType.GET, msg =>
{
Debug.Log(msg.ToString());
}, "TEXT")
);
}
?
原文:https://blog.51cto.com/aonaufly/2939814