using Cysharp.Threading.Tasks;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using UnityEngine;
using UnityEngine.Networking;
public static class HttpHelper
{
///
/// 异步发送HTTP POST请求到指定的URL,包含JSON数据和自定义头部。
///
/// POST请求的目标URL。
/// 要序列化为JSON并在请求体中发送的对象(传入后会进行自动序列化)。
/// 包含要在请求中包含的自定义HTTP头部的字典,请使用PostHeader类的方法。
/// 包含响应状态和消息的WebRequestResult。
///
/// 该方法将数据对象序列化为JSON,通过UnityWebRequest发送,并处理成功和失败的响应。
///
public static async UniTask PostAsync(string url, object data, Dictionary headers)
{
byte[] bytes = null;
if (data != null)
{
var jsonData = JsonUtility.ToJson(data);
bytes = Encoding.UTF8.GetBytes(jsonData);
}
UnityWebRequest www = new UnityWebRequest(url, UnityWebRequest.kHttpVerbPOST)
{
uploadHandler = bytes != null ? new UploadHandlerRaw(bytes) : null,
downloadHandler = new DownloadHandlerBuffer(),
};
foreach (var header in headers)
{
www.SetRequestHeader(header.Key, header.Value);
}
try
{
await www.SendWebRequest();
if (www.result != UnityWebRequest.Result.Success)
{
DebugUtil.LogError(www.downloadHandler.text);
return new WebRequestResult { code = -1, message = www.downloadHandler.text };
}
else
{
DebugUtil.Log("Http请求成功,返回结果" + www.downloadHandler.text);
return new WebRequestResult { code = 0, message = www.downloadHandler.text };
}
}
catch (UnityWebRequestException e)
{
DebugUtil.LogError(e);
return new WebRequestResult { code = -1, message = e.Message };
}
}
public static async UniTask GetAsync(string url, Dictionary headers)
{
UnityWebRequest www = new UnityWebRequest(url, UnityWebRequest.kHttpVerbGET)
{
downloadHandler = new DownloadHandlerBuffer(),
};
foreach (var header in headers)
{
www.SetRequestHeader(header.Key, header.Value);
}
try
{
await www.SendWebRequest();
if (www.result != UnityWebRequest.Result.Success)
{
DebugUtil.LogError(www.downloadHandler.text);
return new WebRequestResult { code = -1, message = www.downloadHandler.text };
}
else
{
DebugUtil.Log("Http请求成功,返回结果" + www.downloadHandler.text);
return new WebRequestResult { code = 0, message = www.downloadHandler.text };
}
}
catch (UnityWebRequestException e)
{
DebugUtil.LogError(e);
return new WebRequestResult { code = -1, message = e.Message };
}
}
}
public class WebRequestResult
{
///
/// 结果码
///
public int code;
///
/// downloadHandler的text内容
///
public string message;
}
///
/// 头部加密
///
public partial class PostHeader
{
///
/// 头部加密信息
///
///
///
public static Dictionary PostHeaderInfo(Dictionary param)
{
DateTimeOffset now = DateTimeOffset.UtcNow;
string timeStamp = now.ToUnixTimeSeconds().ToString();
var encodeData = new EncodeData(param);
string encodeStr = encodeData.GetEncodeData();
var md5 = EncodeData.GetMd5Hash(encodeStr);
string linkStr = md5 + key;
string sign = EncodeData.GetSha256Hash(linkStr);
Dictionary header = new();
header["signature"] = sign;
header["accessKey"] = accessKey;
header["timestamp"] = timeStamp;
header["Content-Type"] = "application/json;charset=utf-8";
return header;
}
class EncodeData
{
Dictionary data = new Dictionary();
public EncodeData(Dictionary data)
{
this.data = data;
}
public string GetEncodeData()
{
List key = data.Keys.Where(k => k != "signature").ToList();
key.Sort();
List keyValuePairs = key.Select(k => k + "=" + data[k]).ToList();
string concatenate = string.Join("&", keyValuePairs);
//DebugUtil.Log("排序结果:" + concatenate);
return concatenate;
}
public static string GetMd5Hash(string input)
{
using (MD5 md5 = MD5.Create())
{
byte[] inputBytes = Encoding.UTF8.GetBytes(input);
byte[] hashBytes = md5.ComputeHash(inputBytes);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < hashBytes.Length; i++)
{
sb.Append(hashBytes[i].ToString("x2"));
}
return sb.ToString();
}
}
public static string GetSha256Hash(string input)
{
using (SHA256 sha256 = SHA256.Create())
{
byte[] inputBytes = Encoding.UTF8.GetBytes(input);
byte[] hashBytes = sha256.ComputeHash(inputBytes);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < hashBytes.Length; i++)
{
sb.Append(hashBytes[i].ToString("x2"));
}
return sb.ToString();
}
}
}
}