WX-Game1/Assets/Scripts/test.cs

243 lines
8.1 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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;
/// <summary>
/// 网络请求测试类 - 展示WebRequestManager的各种功能用法
/// 包含GET、POST、认证、错误处理等完整测试案例
/// </summary>
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<string, string>
{
// 只需要传业务参数appkey、timestamp、sign会自动添加
};
// 使用WebRequestManager发送请求
PostJsonWithWebRequestManager(body);
}
/// <summary>
/// 使用WebRequestManager发送POST请求
/// </summary>
void PostJsonWithWebRequestManager(Dictionary<string, string> 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}");
}
);
}
/// <summary>
/// 原始方法(保留作为参考)
/// </summary>
IEnumerator PostJson(Dictionary<string, object> 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}");
}
}
/// <summary>
/// 把字典转成 key=value&key2=value2
/// </summary>
private static string ToFormUrlEncoded(Dictionary<string, object> body)
{
var list = new List<string>();
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();
}
/// <summary>
/// 测试GET请求with sign
/// </summary>
[ContextMenu("测试GET请求with sign")]
public void TestGetRequestWithSign()
{
// 设置配置
Apis.SetAppKey(appKey);
Apis.SetAppSecret(appSecret);
Apis.SetToken(tokenValue);
// 业务参数
var signParams = new Dictionary<string, string>
{
// 只需要传业务参数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}");
}
);
}
/// <summary>
/// 测试异步POST请求with sign
/// </summary>
[ContextMenu("测试异步POST请求with sign")]
public async void TestAsyncPostRequestWithSign()
{
try
{
// 设置配置
Apis.SetAppKey(appKey);
Apis.SetAppSecret(appSecret);
Apis.SetToken(tokenValue);
// 业务参数
var signParams = new Dictionary<string, string>
{
// 只需要传业务参数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}");
}
}
/// <summary>
/// 测试异步GET请求with sign
/// </summary>
[ContextMenu("测试异步GET请求with sign")]
public async void TestAsyncGetRequestWithSign()
{
try
{
// 设置配置
Apis.SetAppKey(appKey);
Apis.SetAppSecret(appSecret);
Apis.SetToken(tokenValue);
// 业务参数
var signParams = new Dictionary<string, string>
{
// 只需要传业务参数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}");
}
}
}