using Newtonsoft.Json.Linq;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.Networking;
///
///整合JSON
///
public static class CombineJSON
{
//public static List jsons = new List();
public static Dictionary jsonsDic = new Dictionary();
#region 直连
///
/// 获取所有设备API
///
///
public static string GetCombineJSON()
{
//创建一个JArray对象,用于存储多个JSON 对象
JArray jsonArray = new JArray();
// 解析JSON字符串,并添加到JArray
foreach (var item in jsonsDic.Values)
{
var jsonObj = JObject.Parse(item);
jsonArray.Add(jsonObj);
}
//创建一个包含JArray的JObject对象
JObject resultObj = new JObject();
resultObj["data"] = jsonArray;
//将整合后的JSON输出成字符串
string resultJson = resultObj.ToString();
return resultJson;
}
///
/// POST修改数据的请求
///
///
///
///
///
public static async Task UpdateJson_POST(string apiUrl, string token, string newData)
{
var client = new HttpClient();
var request = new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri = new Uri(apiUrl),
Headers =
{
{ "X-Token", token },
},
Content = new StringContent(newData)
{
Headers =
{
ContentType = new MediaTypeHeaderValue("application/json")
}
}
};
using (var response = await client.SendAsync(request))
{
response.EnsureSuccessStatusCode();
var body = await response.Content.ReadAsStringAsync();
return body;
}
}
///
/// POST获取数据的请求
///
///
///
///
public static async Task GetJson_POST(string apiUrl, string token)
{
using (HttpClient httpClient = new HttpClient())
{
Debug.Log(apiUrl + "=aaaaaa=");
var client = new HttpClient();
var request = new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri = new Uri(apiUrl),
Headers =
{
{ "X-Token", token },
},
};
using (var response = await client.SendAsync(request))
{
Debug.Log(apiUrl + "=bbbbbbb=");
response.EnsureSuccessStatusCode();
var body = await response.Content.ReadAsStringAsync();
Debug.Log(body);
return (body);
}
}
}
///
/// 获取GET接口
///
///
///
public static async Task GetJson_GET(string apiUrl)
{
using (var httpClient = new HttpClient())
{
using (var response = await httpClient.GetAsync(apiUrl))
{
if (response.IsSuccessStatusCode)
{
string jsonResult = await response.Content.ReadAsStringAsync();
// 处理返回的JSON数据
Debug.Log(jsonResult);
return jsonResult;
}
else
{
Debug.Log("请求GET接口失败: " + response.StatusCode);
return null;
}
}
}
}
#endregion
#region 协程调用接口
///
/// POST获取数据的请求(无参)
///
///
///
///
///
public static IEnumerator GetJson_POST(string apiUrl, string token, Action callback)
{
//using (UnityWebRequest request = UnityWebRequest.Post(apiUrl, ""))
UnityWebRequest request = new UnityWebRequest(apiUrl, "POST");
{
request.SetRequestHeader("X-Token", token);
request.SetRequestHeader("Content-Type", "application/json");
DownloadHandlerBuffer dH = new DownloadHandlerBuffer();
request.downloadHandler = dH;
//request.timeout = 15;
yield return request.SendWebRequest();
if (!request.isNetworkError && !request.isHttpError)
{
// 等待一帧
yield return null;
// 检查请求是否已完成
while (!request.isDone)
{
yield return null;
}
//if (request.downloadHandler.text != null)
if (!string.IsNullOrEmpty(request.downloadHandler.text))
//byte[] responseData = request.downloadHandler.data;
//if (responseData != null && responseData.Length > 0)
{
string responseText = request.downloadHandler.text;
//responseText = Decrypt(responseText);
//Debug.Log(responseText);
//string responseText = Encoding.UTF8.GetString(responseData);
callback(responseText);
}
else
{
Debug.Log(apiUrl + " request.downloadHandler.text为null");
callback.Invoke(null);
}
}
else
{
Debug.Log(apiUrl + " 请求POST接口失败: " + request.error + "\nURL: " + apiUrl + "\nrequest.downloadHandler:" + /*Decrypt*/(request.downloadHandler.text));
callback.Invoke(null);
}
}
}
///
/// POST数据的请求(有参)
///
///
///
///
///
///
public static IEnumerator UpdateJson_POST(string apiUrl, string token, string newData, Action callback)
{
newData = Encrypt(newData);
//using (UnityWebRequest request = new UnityWebRequest(apiUrl, "POST"))
UnityWebRequest request = new UnityWebRequest(apiUrl, "POST");
{
request.SetRequestHeader("X-Token", token);
request.SetRequestHeader("Content-Type", "application/json");
byte[] bodyRaw = System.Text.Encoding.UTF8.GetBytes(newData);
DownloadHandlerBuffer dH = new DownloadHandlerBuffer();
request.uploadHandler = new UploadHandlerRaw(bodyRaw);
request.downloadHandler = new DownloadHandlerBuffer();
request.downloadHandler = dH;
//request.timeout = 15;
yield return request.SendWebRequest();
if (request.result == UnityWebRequest.Result.Success)
{
// 等待一帧
yield return null;
// 检查请求是否已完成
while (!request.isDone)
{
yield return null;
}
//if (request.downloadHandler.text != null)
if (!string.IsNullOrEmpty(request.downloadHandler.text))
//byte[] responseData = request.downloadHandler.data;
//if (responseData != null && responseData.Length > 0)
{
string responseText = request.downloadHandler.text;
//responseText = Decrypt(responseText);
//string responseText = Encoding.UTF8.GetString(responseData);
callback?.Invoke(responseText);
}
else
{
Debug.Log(apiUrl + " request.downloadHandler.text为空");
callback.Invoke(null);
}
}
else
{
Debug.Log(apiUrl + " 请求POST接口失败: " + request.error + "\nURL: " + apiUrl + "\nrequest.downloadHandler:" + /*Decrypt*/(request.downloadHandler.text));
callback.Invoke(null);
}
}
}
///
/// 获取GET接口
///
///
///
public static IEnumerator GetJson_GET(string apiUrl, Action callback)
{
using (UnityWebRequest request = UnityWebRequest.Get(apiUrl))
{
yield return request.SendWebRequest();
if (!request.isNetworkError && !request.isHttpError)
{
if (request.downloadHandler.text != null)
{
string jsonResult = request.downloadHandler.text;
//Debug.Log(jsonResult);
callback?.Invoke(jsonResult);
}
else
{
Debug.Log("request.downloadHandler.text为null");
callback.Invoke(null);
}
}
else
{
Debug.Log("请求GET接口失败: " + request.error);
callback.Invoke(null);
}
}
}
public static IEnumerator GetJson_GET(string apiUrl, string token, Action callback)
{
//using (UnityWebRequest request = UnityWebRequest.Get(apiUrl))
UnityWebRequest request = UnityWebRequest.Get(apiUrl);
{
request.SetRequestHeader("X-Token", token);
DownloadHandlerBuffer dH = new DownloadHandlerBuffer();
request.downloadHandler = dH;
//request.timeout = 15;
yield return request.SendWebRequest();
if (request.result == UnityWebRequest.Result.Success)
{
// 等待一帧
yield return null;
// 检查请求是否已完成
while (!request.isDone)
{
yield return null;
}
//string responseBody = request.downloadHandler.text;
//if (request.downloadHandler.text != null)
if (!string.IsNullOrEmpty(request.downloadHandler.text))
// byte[] responseData = request.downloadHandler.data;
//if (responseData != null && responseData.Length > 0)
{
string responseText = request.downloadHandler.text;
//string responseText = Encoding.UTF8.GetString(responseData);
callback?.Invoke(responseText);
}
else
{
Debug.Log(apiUrl + " request.downloadHandler.text为空");
callback.Invoke(null);
}
}
else
{
Debug.Log(apiUrl + " 请求Get接口失败: " + request.error + "\nURL: " + apiUrl + "\nrequest.downloadHandler:" + request.downloadHandler.text);
callback.Invoke(null);
}
}
}
public static IEnumerator GetJson_POST(string apiUrl, string token, int looptime, Action callback)
{
while (true)
{
UnityWebRequest request = new UnityWebRequest(apiUrl, "POST");
{
request.SetRequestHeader("X-Token", token);
request.SetRequestHeader("Content-Type", "application/json");
DownloadHandlerBuffer dH = new DownloadHandlerBuffer();
request.downloadHandler = dH;
request.timeout = 15;
yield return request.SendWebRequest();
if (!request.isNetworkError && !request.isHttpError)
{
// 等待一帧
yield return null;
// 检查请求是否已完成
while (!request.isDone)
{
yield return null;
}
//if (request.downloadHandler.text != null)
if (!string.IsNullOrEmpty(request.downloadHandler.text))
// byte[] responseData = request.downloadHandler.data;
//if (responseData != null && responseData.Length > 0)
{
string responseText = request.downloadHandler.text;
//Debug.Log(responseText);
//string responseText = Encoding.UTF8.GetString(responseData);
callback(responseText);
}
else
{
Debug.Log("request.downloadHandler.text为null");
}
}
else
{
Debug.Log("请求POST接口失败: " + request.error + "\nURL: " + apiUrl + "\nrequest.downloadHandler:" + request.downloadHandler.text);
}
}
yield return new WaitForSeconds(looptime);
}
}
#endregion
public static Texture2D Base64StringToTexture(string base64Str)
{
try
{
//将base64头部信息替换
base64Str = base64Str.Replace("data:image/png;base64,", "").Replace("data:image/jgp;base64,", "")
.Replace("data:image/jpg;base64,", "").Replace("data:image/jpeg;base64,", "");
byte[] bytes = Convert.FromBase64String(base64Str);
Texture2D texture = new Texture2D(10, 10);
texture.LoadImage(bytes);
return texture;
}
catch (Exception ex)
{
return null;
}
}
public static string Decrypt(string cipherText, string key = "1234567890adbcde", string iv = "1234567890hjlkew")
{
return cipherText;
try
{
byte[] keyBytes = Encoding.UTF8.GetBytes(key);
byte[] ivBytes = Encoding.UTF8.GetBytes(iv);
using (var aesAlg = System.Security.Cryptography.Aes.Create())
{
aesAlg.Key = keyBytes;
aesAlg.IV = ivBytes;
aesAlg.Mode = System.Security.Cryptography.CipherMode.CBC;
aesAlg.Padding = System.Security.Cryptography.PaddingMode.None; // Set to None initially
var decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
byte[] cipherBytes = Convert.FromBase64String(cipherText);
using (var msDecrypt = new System.IO.MemoryStream(cipherBytes))
{
using (var csDecrypt = new System.Security.Cryptography.CryptoStream(msDecrypt, decryptor, System.Security.Cryptography.CryptoStreamMode.Read))
{
using (var srDecrypt = new System.IO.StreamReader(csDecrypt))
{
return srDecrypt.ReadToEnd();
}
}
}
}
}
catch (Exception ex)
{
Debug.LogError("Decryption Error: " + ex.Message);
return null;
}
}
public static string Encrypt(string plainText, string key = "1234567890adbcde", string iv = "1234567890hjlkew")
{
return plainText;
using (AesManaged aesAlg = new AesManaged())
{
aesAlg.Key = Encoding.UTF8.GetBytes(key);
aesAlg.IV = Encoding.UTF8.GetBytes(iv);
ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
byte[] encryptedBytes;
using (var msEncrypt = new System.IO.MemoryStream())
{
using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
byte[] plainBytes = Encoding.UTF8.GetBytes(plainText);
csEncrypt.Write(plainBytes, 0, plainBytes.Length);
}
encryptedBytes = msEncrypt.ToArray();
}
return Convert.ToBase64String(encryptedBytes);
}
}
}