NLDClient-yudde/ProjectNLD/Assets/Code/Scripts/Gameplay/Net/Utils/HttpHelper.cs

193 lines
6.2 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

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
{
/// <summary>
/// 异步发送HTTP POST请求到指定的URL包含JSON数据和自定义头部。
/// </summary>
/// <param name="url">POST请求的目标URL。</param>
/// <param name="data">要序列化为JSON并在请求体中发送的对象(传入后会进行自动序列化)。</param>
/// <param name="headers">包含要在请求中包含的自定义HTTP头部的字典请使用PostHeader类的方法。</param>
/// <returns>包含响应状态和消息的WebRequestResult。</returns>
/// <remarks>
/// 该方法将数据对象序列化为JSON通过UnityWebRequest发送并处理成功和失败的响应。
/// </remarks>
public static async UniTask<WebRequestResult> PostAsync(string url, object data, Dictionary<string, string> 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<WebRequestResult> GetAsync(string url, Dictionary<string, string> 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
{
/// <summary>
/// 结果码
/// </summary>
public int code;
/// <summary>
/// downloadHandler的text内容
/// </summary>
public string message;
}
/// <summary>
/// 头部加密
/// </summary>
public partial class PostHeader
{
/// <summary>
/// 头部加密信息
/// </summary>
/// <param name="param"></param>
/// <returns></returns>
public static Dictionary<string, string> PostHeaderInfo(Dictionary<string, string> 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<string, string> header = new();
header["signature"] = sign;
header["accessKey"] = accessKey;
header["timestamp"] = timeStamp;
header["Content-Type"] = "application/json;charset=utf-8";
return header;
}
class EncodeData
{
Dictionary<string, string> data = new Dictionary<string, string>();
public EncodeData(Dictionary<string, string> data)
{
this.data = data;
}
public string GetEncodeData()
{
List<string> key = data.Keys.Where(k => k != "signature").ToList();
key.Sort();
List<string> 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();
}
}
}
}