鸿蒙HarmonyOS NEXT(开发进阶)实现一个基于鸿蒙API的HTTP服务器实践案例

  鸿蒙NEXT开发实战往期必看文章:

一分钟了解”纯血版!鸿蒙HarmonyOS Next应用开发!

“非常详细的” 鸿蒙HarmonyOS Next应用开发学习路线!(从零基础入门到精通)

HarmonyOS NEXT应用开发案例实践总结合(持续更新......)

HarmonyOS NEXT应用开发性能优化实践总结(持续更新......)


1. 鸿蒙HTTP服务器可行性分析

看到这个题目,可能有的小伙伴会有一些疑问:

“鸿蒙API从9到12我都翻烂了,也没见提供HTTP服务器的接口啊”

“我BUG写得少,你可不要骗我”

的确,目前的鸿蒙API没有提供HTTP服务端的实现接口,但是我们知道,HTTP协议是基于TCP的,而鸿蒙API10提供了TCPSocketServer类,包含了如下几个关键接口:

listen(address: NetAddress): Promise<void>

监听方法,绑定IP地址和端口,端口可以指定或由系统随机分配。成功调用该方法后,TCPSocketServer对象监听并接受与此套接字建立的TCPSocket连接。

on(type: 'connect', callback: Callback<TCPSocketConnection>): void

订阅TCPSocketServer的连接事件,在新的客户端套接字连接上以后,会触发callback回调,在回调中包含TCPSocketConnection对象,该对象就表示TCPSocket客户端与服务端的连接。

TCPSocketConnection是服务端和客户端通讯的基础,提供了发送数据到客户端的方法:

send(options: TCPSendOptions): Promise<void>

还提供了订

<think>我们正在开发鸿蒙HarmonyOS Next应用,需要使用HTTP工具类。根据引用内容,鸿蒙API内置了HTTP客户端支持(HttpRequest),但暂不支持HTTP服务端(不过可以通过TCP Server自行实现)。用户的需求是获取HTTP工具类的开发使用方法和示例代码。 根据引用[1]和引用[3],我们可以知道: 1. 鸿蒙提供了HttpRequest类用于HTTP客户端请求。 2. 引用[3]中提供了一个示例工程结构,并提到在http.ts文件中封装了http参数和发起请求的接口。 因此,我们将重点介绍如何使用HttpRequest类发起HTTP请求,并提供一个简单的示例代码。 步骤: 1. 配置权限:在config.json中声明网络权限。 2. 导入模块:在代码中导入http模块。 3. 创建HttpRequest对象。 4. 设置请求参数(URL、方法、头部、响应类型等)。 5. 发起请求并处理响应。 注意:鸿蒙HTTP请求是异步的,我们可以使用Promise或者回调函数来处理响应。 示例代码(TypeScript): 以下是一个简单的GET请求示例,以及一个POST请求示例。 首先,确保在config.json中声明网络权限: ```json { "module": { "reqPermissions": [ { "name": "ohos.permission.INTERNET" } ] } } ``` 然后,在代码中: ```typescript import http from '@ohos.net.http'; // 创建HttpRequest对象 let httpRequest = http.createHttp(); // 示例1:GET请求 async function httpGet() { let url = 'https://example.com/api/get'; try { let response = await httpRequest.request( url, { method: http.RequestMethod.GET, header: { 'Content-Type': 'application/json' } } ); // 请求成功,response.result为响应体 console.log('GET Result: ' + JSON.stringify(response.result)); console.log('GET Code: ' + response.responseCode); } catch (error) { console.error('GET Error: ' + JSON.stringify(error)); } } // 示例2:POST请求 async function httpPost() { let url = 'https://example.com/api/post'; try { let response = await httpRequest.request( url, { method: http.RequestMethod.POST, header: { 'Content-Type': 'application/json' }, extraData: { key1: 'value1', key2: 'value2' } } ); console.log('POST Result: ' + JSON.stringify(response.result)); console.log('POST Code: ' + response.responseCode); } catch (error) { console.error('POST Error: ' + JSON.stringify(error)); } } ``` 说明: 1. 使用`http.createHttp()`创建一个HttpRequest实例。 2. 调用`request`方法发起请求,第一个参数是URL,第二个参数是配置对象,包括: - method: 请求方法(GET, POST等) - header: 请求头 - extraData: 请求体(POST请求时使用) 3. 使用async/await处理异步请求,也可以使用回调函数(通过配置对象中的readable和writable属性,但推荐使用Promise方式)。 注意:在实际开发中,建议将HTTP请求封装成工具类,以便复用和管理。 封装示例(参考引用[3]中的http.ts): 我们可以创建一个HttpUtil类,封装GET和POST方法。 http.ts: ```typescript import http from '@ohos.net.http'; export default class HttpUtil { private httpRequest: http.HttpRequest; constructor() { this.httpRequest = http.createHttp(); } // GET请求 async get(url: string, headers: Object = {}): Promise<any> { try { let response = await this.httpRequest.request(url, { method: http.RequestMethod.GET, header: headers }); return response.result; } catch (error) { console.error('HttpUtil GET Error: ' + JSON.stringify(error)); throw error; } } // POST请求 async post(url: string, data: Object, headers: Object = {'Content-Type': 'application/json'}): Promise<any> { try { let response = await this.httpRequest.request(url, { method: http.RequestMethod.POST, header: headers, extraData: data }); return response.result; } catch (error) { console.error('HttpUtil POST Error: ' + JSON.stringify(error)); throw error; } } } ``` 使用封装好的工具类: ```typescript import HttpUtil from './HttpUtil'; // 在页面中 let httpUtil = new HttpUtil(); // 发送GET请求 httpUtil.get('https://example.com/api/get').then(result => { console.log('Result: ' + JSON.stringify(result)); }).catch(error => { console.error('Error: ' + JSON.stringify(error)); }); // 发送POST请求 let data = { key: 'value' }; httpUtil.post('https://example.com/api/post', data).then(result => { console.log('Result: ' + JSON.stringify(result)); }).catch(error => { console.error('Error: ' + JSON.stringify(error)); }); ``` 注意事项: 1. 确保设备有网络连接。 2. 注意异步处理,避免阻塞UI。 3. 错误处理要完善。 以上就是在鸿蒙HarmonyOS Next中使用HTTP工具类的基本方法和示例代码。 根据用户需求,我们提供了开发步骤、示例代码以及封装工具类的建议。用户可以根据实际需求调整封装类。 §§相关问题§§ 1. 鸿蒙HarmonyOS Next中如何处理HTTPS请求? 2. 如何设置HTTP请求的超时时间? 3. 鸿蒙HTTP请求支持哪些方法? 4. 如何上传文件?</think>### 鸿蒙 HarmonyOS Next HTTP 工具类开发指南 #### 一、开发准备 1. **权限声明** 在 `module.json5` 中添加网络权限: ```json "requestPermissions": [ { "name": "ohos.permission.INTERNET" } ] ``` 2. **依赖导入** 在代码中导入 HTTP 模块: ```typescript import http from '@ohos.net.http'; ``` #### 二、核心工具类封装 ```typescript // HttpUtil.ts export default class HttpUtil { private httpRequest: http.HttpRequest; constructor() { this.httpRequest = http.createHttp(); } // GET请求 async get(url: string, params?: Record<string, string>): Promise<any> { const fullUrl = params ? `${url}?${new URLSearchParams(params)}` : url; return this.request(fullUrl, http.RequestMethod.GET); } // POST请求 async post(url: string, data: object): Promise<any> { return this.request(url, http.RequestMethod.POST, data); } // 统一请求方法 private async request( url: string, method: http.RequestMethod, data?: object ): Promise<any> { try { const response = await this.httpRequest.request(url, { method, header: { 'Content-Type': 'application/json' }, extraData: data ? JSON.stringify(data) : undefined }); if (response.responseCode === http.ResponseCode.OK) { return JSON.parse(response.result.toString()); } else { throw new Error(`HTTP Error ${response.responseCode}`); } } catch (error) { console.error(`Request failed: ${JSON.stringify(error)}`); throw error; } } } ``` #### 三、使用示例 ```typescript // MainPage.ets import HttpUtil from './HttpUtil'; @Entry @Component struct MainPage { private http: HttpUtil = new HttpUtil(); async fetchData() { try { // GET示例 const userData = await this.http.get( 'https://api.example.com/users', { id: '123' } ); // POST示例 const loginRes = await this.http.post( 'https://api.example.com/login', { username: 'test', password: '123456' } ); console.log('Login response:', loginRes); } catch (error) { console.error('API Error:', error); } } build() { Column() { Button('获取数据') .onClick(() => this.fetchData()) } } } ``` #### 四、关键功能说明 1. **请求方法支持** - 支持所有标准方法:`GET`, `POST`, `PUT`, `DELETE` 等 - 通过 `http.RequestMethod` 枚举调用 2. **参数处理**: - GET 参数自动 URL 编码 - POST 数据自动 JSON 序列化 3. **错误处理**: - 自动捕获网络异常 - 验证 HTTP 状态码(200-299 视为成功) 4. **响应处理**: - 自动将响应体解析为 JSON 对象 - 原始数据可通过 `response.result` 获取 #### 五、进阶配置 ```typescript // 自定义请求示例 const customRequest = await httpRequest.request( 'https://api.example.com/upload', { method: http.RequestMethod.PUT, header: { 'Authorization': 'Bearer token', 'Custom-Header': 'value' }, connectTimeout: 30_000, // 30秒超时 usingCache: true // 启用缓存 } ); ``` > **注意事项**: > 1. 鸿蒙 NEXTHTTP 客户端**不支持服务端开发**,需通过 `TCPSocketServer` 自行实现 [^2] > 2. 使用 HTTPS 需配置网络安全策略 > 3. 文件上传需使用 `@ohos.multimedia.mediaLibrary` 模块
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值