告别拼接URL!手把手教你封装HarmonyOS的POST请求工具类
告别拼接URL手把手教你封装HarmonyOS的POST请求工具类在HarmonyOS应用开发中网络请求是每个开发者都无法绕开的核心功能。很多从Android转战HarmonyOS的开发者会发现原本在Android中通过Retrofit等框架轻松实现的POST请求在HarmonyOS中却需要手动拼接URL参数这不仅让代码显得冗长丑陋更违背了RESTful API的设计原则。本文将带你从工程化角度出发封装一个优雅、安全的POST请求工具类让你的HarmonyOS代码焕然一新。1. 为什么需要封装POST请求工具类在HarmonyOS的http模块中POST请求的参数传递方式常常让开发者感到困惑。与Android不同直接将参数放入extraData并不能被服务端正确接收这导致很多开发者不得不采用GET请求的方式将参数拼接到URL上。这种做法至少存在三个明显问题安全性隐患URL中的参数会明文暴露在日志和浏览器历史记录中代码可读性差参数拼接使得URL变得冗长难以维护违背RESTful规范POST请求的参数应该放在请求体中而非URL以下是一个典型的问题代码示例requestUserInfo({ url: https://api.example.com/login?usernameadminpassword123456, method: http.RequestMethod.POST, extraData: {} }).then(...)2. 设计POST请求工具类的核心功能一个完善的POST请求工具类应该具备以下核心能力参数自动序列化支持对象参数自动转换为JSON字符串Content-Type自动设置根据参数类型自动配置合适的请求头统一错误处理集中管理网络错误和业务错误请求拦截机制支持添加公共参数或认证信息响应数据解析自动将响应数据反序列化为指定类型我们可以先定义工具类的基本结构class HttpUtil { private static instance: HttpUtil; private baseUrl: string; private headers: Recordstring, string {}; private constructor(baseUrl: string) { this.baseUrl baseUrl; this.initDefaultHeaders(); } public static getInstance(baseUrl: string): HttpUtil { if (!HttpUtil.instance) { HttpUtil.instance new HttpUtil(baseUrl); } return HttpUtil.instance; } private initDefaultHeaders(): void { this.headers { Content-Type: application/json;charsetutf-8 }; } // 其他方法将在后续实现 }3. 实现核心POST请求方法现在我们来实现最关键的post方法该方法需要处理参数序列化、请求头设置和错误处理public async postT(endpoint: string, params?: object): PromiseT { try { const url ${this.baseUrl}${endpoint}; const response await requestT({ url: url, method: http.RequestMethod.POST, header: this.headers, extraData: params ? JSON.stringify(params) : undefined }); return this.handleResponseT(response); } catch (error) { return this.handleError(error); } } private handleResponseT(response: any): T { if (response.code ! 200) { throw new Error(response.message || 请求失败); } return response.data as T; } private handleError(error: any): never { console.error(请求失败: ${JSON.stringify(error)}); throw new Error(error.message || 网络请求异常); }使用这个工具类之前的登录请求可以简化为const http HttpUtil.getInstance(https://api.example.com); http.postUserInfo(/login, { username: admin, password: 123456 }).then(userInfo { console.info(登录成功: ${JSON.stringify(userInfo)}); }).catch(error { console.error(登录失败: ${error.message}); });4. 高级功能扩展基础功能实现后我们可以进一步扩展工具类的实用性4.1 添加请求拦截器private interceptors: Array(config: RequestConfig) RequestConfig []; public addInterceptor(interceptor: (config: RequestConfig) RequestConfig): void { this.interceptors.push(interceptor); } private applyInterceptors(config: RequestConfig): RequestConfig { return this.interceptors.reduce((cfg, interceptor) interceptor(cfg), config); }4.2 支持多种Content-Typepublic setContentType(type: json | form): void { this.headers[Content-Type] type json ? application/json;charsetutf-8 : application/x-www-form-urlencoded; } private serializeParams(params: object, contentType: string): string { if (contentType.includes(x-www-form-urlencoded)) { return Object.entries(params) .map(([key, value]) ${encodeURIComponent(key)}${encodeURIComponent(value)}) .join(); } return JSON.stringify(params); }4.3 添加超时设置public setTimeout(timeout: number): void { this.timeout timeout; } private getRequestConfig(endpoint: string, method: http.RequestMethod, data?: any): RequestConfig { return { url: ${this.baseUrl}${endpoint}, method: method, header: this.headers, extraData: data, connectTimeout: this.timeout, readTimeout: this.timeout }; }5. 完整工具类实现将上述功能整合我们得到完整的HttpUtil工具类import http from ohos.net.http; import { RequestConfig, ResponseError } from ohos.net.http; type HttpMethod GET | POST | PUT | DELETE; class HttpUtil { private static instance: HttpUtil; private baseUrl: string; private headers: Recordstring, string {}; private interceptors: Array(config: RequestConfig) RequestConfig []; private timeout: number 60000; private constructor(baseUrl: string) { this.baseUrl baseUrl.endsWith(/) ? baseUrl.slice(0, -1) : baseUrl; this.initDefaultHeaders(); } public static getInstance(baseUrl: string): HttpUtil { if (!HttpUtil.instance) { HttpUtil.instance new HttpUtil(baseUrl); } return HttpUtil.instance; } private initDefaultHeaders(): void { this.headers { Content-Type: application/json;charsetutf-8, Accept: application/json }; } public async requestT( method: HttpMethod, endpoint: string, params?: object ): PromiseT { try { const serializedData this.serializeParams(params || {}, this.headers[Content-Type]); const config this.applyInterceptors({ url: ${this.baseUrl}${endpoint}, method: this.mapMethod(method), header: this.headers, extraData: serializedData, connectTimeout: this.timeout, readTimeout: this.timeout }); const response await requestT(config); return this.handleResponseT(response); } catch (error) { return this.handleError(error); } } public async postT(endpoint: string, params?: object): PromiseT { return this.requestT(POST, endpoint, params); } // 其他HTTP方法实现类似此处省略... private mapMethod(method: HttpMethod): http.RequestMethod { const map: RecordHttpMethod, http.RequestMethod { GET: http.RequestMethod.GET, POST: http.RequestMethod.POST, PUT: http.RequestMethod.PUT, DELETE: http.RequestMethod.DELETE }; return map[method]; } private serializeParams(params: object, contentType: string): string { if (!params) return ; if (contentType.includes(x-www-form-urlencoded)) { return Object.entries(params) .map(([key, value]) ${encodeURIComponent(key)}${encodeURIComponent(value)}) .join(); } return JSON.stringify(params); } private handleResponseT(response: any): T { if (response.code ! 200) { throw new Error(response.message || 请求失败); } return response.data as T; } private handleError(error: ResponseError): never { console.error(请求失败: ${JSON.stringify(error)}); throw new Error(error.message || 网络请求异常); } public addInterceptor(interceptor: (config: RequestConfig) RequestConfig): void { this.interceptors.push(interceptor); } private applyInterceptors(config: RequestConfig): RequestConfig { return this.interceptors.reduce((cfg, interceptor) interceptor(cfg), config); } public setContentType(type: json | form): void { this.headers[Content-Type] type json ? application/json;charsetutf-8 : application/x-www-form-urlencoded; } public setTimeout(timeout: number): void { this.timeout timeout; } public setHeader(key: string, value: string): void { this.headers[key] value; } } export default HttpUtil;6. 实际应用示例让我们看几个实际使用这个工具类的例子6.1 用户登录场景// 初始化HTTP工具 const http HttpUtil.getInstance(https://api.example.com); // 添加全局拦截器用于添加认证token http.addInterceptor(config { const token PreferencesManager.getInstance().getSync(auth_token); if (token) { config.header config.header || {}; config.header[Authorization] Bearer ${token}; } return config; }); // 登录请求 async function login(username: string, password: string): PromiseUserInfo { try { const user await http.postUserInfo(/auth/login, { username, password }); // 保存token PreferencesManager.getInstance().putSync(auth_token, user.token); return user; } catch (error) { console.error(登录失败:, error.message); throw error; } }6.2 文件上传场景async function uploadFile(fileUri: string): PromiseUploadResult { // 切换为表单格式 http.setContentType(form); const formData new FormData(); formData.append(file, { uri: fileUri, type: image/jpeg, name: photo.jpg }); const result await http.postUploadResult(/files/upload, formData); // 恢复默认JSON格式 http.setContentType(json); return result; }6.3 带参数的分页查询async function fetchArticles(page: number, size: number): PromiseArticle[] { return http.getArticle[](/articles, { page, size, sort: createdAt,desc }); }封装这样一个完善的POST请求工具类后你会发现HarmonyOS的网络请求代码变得简洁、统一且易于维护。更重要的是它遵循了RESTful API的最佳实践参数不再暴露在URL中安全性得到了显著提升。
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2488685.html
如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!