123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122 |
- 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<string, any>, headers?: Record<string, string>): Promise<any> {
- // 拼接查询参数
- 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<string, string>): Promise<any> {
- // 设置默认 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<string, string>): Promise<any> {
- 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, any>): string {
- return Object.keys(params)
- .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
- .join('&');
- }
- }
|