import { _decorator, sys } from 'cc'; /** * HTTP 请求工具类 * 支持 GET/POST 方法,自动处理平台差异 */ export class HttpRequest { /** * 发送 GET 请求 * @param url 请求地址 * @param params 查询参数 (可选) * @param headers 请求头 (可选) */ public static get(url: string, params?: Record, headers?: Record): Promise { // 拼接查询参数 const queryString = params ? this.serializeParams(params) : ''; const fullUrl = queryString ? `${url}?${queryString}` : url; return this.request('GET', fullUrl, null, headers); } /** * 发送 POST 请求 * @param url 请求地址 * @param data 请求体数据 (可选) * @param headers 请求头 (可选) */ public static post(url: string, data?: any, headers?: Record): Promise { // 设置默认 Content-Type const defaultHeaders = { 'Content-Type': 'application/json', ...headers }; return this.request('POST', url, data, defaultHeaders); } /** * 核心请求方法 * @param method HTTP 方法 * @param url 请求地址 * @param data 请求数据 * @param headers 请求头 */ private static request(method: string, url: string, data?: any, headers?: Record): Promise { return new Promise((resolve, reject) => { // 微信小游戏平台使用 wx.request if (sys.platform === sys.Platform.WECHAT_GAME) { window['wx'].request({ url, method: method as any, data, header: headers, success: (res) => { if (res.statusCode >= 200 && res.statusCode < 300) { resolve(res.data); } else { reject(new Error(`HTTP Error: ${res.statusCode}`)); } }, fail: (err) => { reject(new Error(`Request failed: ${err.errMsg}`)); } }); } // 其他平台使用 XMLHttpRequest else { const xhr = new XMLHttpRequest(); xhr.open(method, url, true); // 设置请求头 if (headers) { for (const key in headers) { if (headers.hasOwnProperty(key)) { xhr.setRequestHeader(key, headers[key]); } } } xhr.onreadystatechange = () => { if (xhr.readyState === 4) { if (xhr.status >= 200 && xhr.status < 300) { try { resolve(JSON.parse(xhr.responseText)); } catch (e) { resolve(xhr.responseText); } } else { reject(new Error(`HTTP Error: ${xhr.status}`)); } } }; xhr.onerror = () => { reject(new Error('Network error')); }; // 发送数据 if (data) { if (headers && headers['Content-Type'] === 'application/json') { xhr.send(JSON.stringify(data)); } else { xhr.send(data); } } else { xhr.send(); } } }); } /** * 序列化查询参数 * @param params 参数对象 * @returns 查询字符串 */ private static serializeParams(params: Record): string { return Object.keys(params) .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`) .join('&'); } }