using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using Newtonsoft.Json;
using UnityEngine;
using UnityEngine.Networking;
using WXGame.Network;
using DefaultNamespace;
///
/// 网络请求测试类 - 展示WebRequestManager的各种功能用法
/// 包含GET、POST、认证、错误处理等完整测试案例
///
public class test : MonoBehaviour
{
// ====== 配置区(按你实际情况改)======
[Header("接口根地址+路径")]
public string baseUrl = "https://game.api.njfengwei.cn/uapi";
public string endpoint = "/Friend/addFriend"; // 让对接人给出真实路径
[Header("鉴权/签名配置")]
[SerializeField]private string appKey = "38kisezhasfgxhh98b";
[SerializeField]private string appSecret = "2d6wy8hm8rxbi4xt8dghovggdoodqs57"; // 仅用于本地签名,绝对不要随请求发送
[SerializeField]private string tokenHeaderName = "token"; // 若对方要求把 token 放 header,这里写 header 名称
[SerializeField]private string tokenValue = "ff6b2c9b0f5d615fc6b4bc50dd3737d9a49747b98eb52f685c15fa692638e09f"; // 如果没有就留空
// 示例:脚本启动后发一次请求
private void Start()
{
// 设置配置
Apis.SetAppKey(appKey);
Apis.SetAppSecret(appSecret);
Apis.SetToken(tokenValue);
// 业务参数(这些将进 body 并参与签名;sign 除外)
var body = new Dictionary
{
// 只需要传业务参数,appkey、timestamp、sign会自动添加
};
// 使用WebRequestManager发送请求
PostJsonWithWebRequestManager(body);
}
///
/// 使用WebRequestManager发送POST请求
///
void PostJsonWithWebRequestManager(Dictionary body)
{
// 构建完整URL
string url = baseUrl.TrimEnd('/') + "/" + endpoint.TrimStart('/');
Debug.Log($"[url] {url}");
Debug.Log($"[业务参数] {JsonConvert.SerializeObject(body)}");
Debug.Log($"[token] {tokenValue}");
// 使用WebRequestManager发送POST请求,启用sign签名
WebRequestManager.Instance.PostRequest(
url: url,
enableSign: true,
signParams: body,
onComplete: (result) => {
Debug.Log($"HTTP {result.ResponseCode}");
Debug.Log($"响应内容: {result.ResponseText}");
},
onError: (error) => {
Debug.LogError($"请求失败: {error}");
}
);
}
///
/// 原始方法(保留作为参考)
///
IEnumerator PostJson(Dictionary body)
{
// 1) 生成 sign(等价 PHP 的 getSign)
string sign = SignUtil.GetSign(body, appSecret);
body["sign"] = sign;
// 2) 序列化 JSON(等价 PHP 的 json_encode)
string json = JsonConvert.SerializeObject(body);
// 调试信息:方便对照后端
Debug.Log($"[加密前] {SignUtil.LastPlainText}");
Debug.Log($"[加密后] {sign}");
Debug.Log($"[填入Body] {json}");
Debug.Log($"[token] {tokenValue}");
// 3) 发送 POST(JSON)(等价 PHP 的 http_post_json)
string url = baseUrl.TrimEnd('/') + "/" + endpoint.TrimStart('/');
Debug.Log($"[url] {url}");
var req = new UnityWebRequest(url, "POST");
req.uploadHandler = new UploadHandlerRaw(Encoding.UTF8.GetBytes(json));
req.downloadHandler = new DownloadHandlerBuffer();
req.SetRequestHeader("Content-Type", "application/json; charset=utf-8");
// 若对方要求把 token 放在 Header,这里加;否则把 token 放 body 并参与签名
if (!string.IsNullOrEmpty(tokenValue))
req.SetRequestHeader(tokenHeaderName, tokenValue);
yield return req.SendWebRequest();
// 4) 结果
if (req.result != UnityWebRequest.Result.Success)
{
Debug.LogError($"HTTP {req.responseCode} | {req.error}\n{req.downloadHandler.text}");
}
else
{
Debug.Log($"HTTP {req.responseCode}\n{req.downloadHandler.text}");
}
}
///
/// 把字典转成 key=value&key2=value2
///
private static string ToFormUrlEncoded(Dictionary body)
{
var list = new List();
foreach (var kv in body)
{
string key = UnityWebRequest.EscapeURL(kv.Key);
string val = UnityWebRequest.EscapeURL(kv.Value.ToString());
list.Add($"{key}={val}");
}
return string.Join("&", list);
}
// Unix 时间戳(秒)
private static long GetUnixTimeSeconds()
{
var now = DateTimeOffset.UtcNow;
return now.ToUnixTimeSeconds();
}
///
/// 测试GET请求with sign
///
[ContextMenu("测试GET请求with sign")]
public void TestGetRequestWithSign()
{
// 设置配置
Apis.SetAppKey(appKey);
Apis.SetAppSecret(appSecret);
Apis.SetToken(tokenValue);
// 业务参数
var signParams = new Dictionary
{
// 只需要传业务参数,appkey、timestamp、sign会自动添加
};
string url = baseUrl.TrimEnd('/') + "/" + endpoint.TrimStart('/');
WebRequestManager.Instance.GetRequest(
url: url,
enableSign: true,
signParams: signParams,
onComplete: (result) => {
Debug.Log($"GET请求成功: {result.ResponseCode}");
Debug.Log($"响应内容: {result.ResponseText}");
},
onError: (error) => {
Debug.LogError($"GET请求失败: {error}");
}
);
}
///
/// 测试异步POST请求with sign
///
[ContextMenu("测试异步POST请求with sign")]
public async void TestAsyncPostRequestWithSign()
{
try
{
// 设置配置
Apis.SetAppKey(appKey);
Apis.SetAppSecret(appSecret);
Apis.SetToken(tokenValue);
// 业务参数
var signParams = new Dictionary
{
// 只需要传业务参数,appkey、timestamp、sign会自动添加
};
string url = baseUrl.TrimEnd('/') + "/" + endpoint.TrimStart('/');
var result = await WebRequestManager.Instance.PostRequestAsync(
url: url,
signParams: signParams
);
Debug.Log($"异步POST请求成功: {result.ResponseCode}");
Debug.Log($"响应内容: {result.ResponseText}");
}
catch (Exception ex)
{
Debug.LogError($"异步POST请求失败: {ex.Message}");
}
}
///
/// 测试异步GET请求with sign
///
[ContextMenu("测试异步GET请求with sign")]
public async void TestAsyncGetRequestWithSign()
{
try
{
// 设置配置
Apis.SetAppKey(appKey);
Apis.SetAppSecret(appSecret);
Apis.SetToken(tokenValue);
// 业务参数
var signParams = new Dictionary
{
// 只需要传业务参数,appkey、timestamp、sign会自动添加
};
string url = baseUrl.TrimEnd('/') + "/" + endpoint.TrimStart('/');
var result = await WebRequestManager.Instance.GetRequestAsync(
url: url,
enableSign: true,
signParams: signParams
);
Debug.Log($"异步GET请求成功: {result.ResponseCode}");
Debug.Log($"响应内容: {result.ResponseText}");
}
catch (Exception ex)
{
Debug.LogError($"异步GET请求失败: {ex.Message}");
}
}
}