HarmonyOS HTTP 网络请求:@ohos.net.http

发布时间:2026/7/18 2:06:44
HarmonyOS HTTP 网络请求:@ohos.net.http 适用版本HarmonyOS 6.1API 12及以上验证环境Pura 90 Pro 模拟器HarmonyOS 6.1.1API 24关键概念http.createHttp、request、RequestMethod、responseCode、destroy前言ohos.net.http是 HarmonyOS 官方 HTTP 客户端模块支持 GET/POST/PUT/DELETE、自定义请求头、超时配置、Cookie 处理。本文演示 GET 和 POST 请求的完整写法以及错误处理和资源释放。一、发起 GET 请求import http from ohos.net.http async function doGet(): Promisestring { const client http.createHttp() try { const resp await client.request( https://api.example.com/users/1, { method: http.RequestMethod.GET, header: { Accept: application/json, Authorization: Bearer ${token} }, readTimeout: 5000, // 读取超时毫秒 connectTimeout: 5000 // 连接超时毫秒 } ) if (resp.responseCode 200) { return resp.result as string // 响应体字符串 } else { throw new Error(HTTP ${resp.responseCode}) } } finally { client.destroy() // 必须调用释放底层资源 } }二、发起 POST 请求JSON 体async function doPost(): Promisestring { const client http.createHttp() const body JSON.stringify({ title: HarmonyOS 6.1, content: 新特性介绍, userId: 42 }) try { const resp await client.request( https://api.example.com/posts, { method: http.RequestMethod.POST, header: { Content-Type: application/json, Accept: application/json }, extraData: body, // POST body字符串或 ArrayBuffer readTimeout: 8000, connectTimeout: 8000 } ) if (resp.responseCode 200 resp.responseCode 300) { return resp.result as string } throw new Error(请求失败: HTTP ${resp.responseCode}) } catch (e) { throw new Error(网络错误: ${(e as Error).message}) } finally { client.destroy() } }三、响应对象字段// resp: http.HttpResponse resp.responseCode // HTTP 状态码200、404 等 resp.result // 响应体string | ArrayBuffer resp.header // 响应头Recordstring, string resp.cookies // Set-Cookie 值 resp.performanceTiming // 各阶段耗时DNS、TCP、首字节等四、RequestMethod 枚举http.RequestMethod.GET http.RequestMethod.POST http.RequestMethod.PUT http.RequestMethod.DELETE http.RequestMethod.PATCH http.RequestMethod.OPTIONS http.RequestMethod.HEAD五、错误处理与重试async function fetchWithRetry(url: string, maxRetry: number): Promisestring { let lastError for (let i 0; i maxRetry; i) { const client http.createHttp() try { const resp await client.request(url, { method: http.RequestMethod.GET, readTimeout: 5000, connectTimeout: 5000 }) if (resp.responseCode 200) { return resp.result as string } lastError HTTP ${resp.responseCode} } catch (e) { lastError (e as Error).message } finally { client.destroy() } // 指数退避1s、2s、4s if (i maxRetry - 1) { await new Promisevoid(resolve setTimeout(resolve, 1000 * Math.pow(2, i))) } } throw new Error(重试 ${maxRetry} 次后失败: ${lastError}) }六、配置网络权限在entry/src/main/module.json5中添加权限{ module: { requestPermissions: [ { name: ohos.permission.INTERNET } ] } }模拟器运行截图初始状态GET 请求完成点击「GET 请求」后向httpbin.org/get发起真实 HTTP 请求显示响应状态码200、耗时毫秒和响应体预览。实测结果请求URL状态码耗时GEThttpbin.org/get200~300-800msPOSTjsonplaceholder.typicode.com/posts201~200-500ms常见问题Q为什么请求失败报connect ECONNREFUSEDA检查模拟器的网络连接。在真机和模拟器上HTTP 请求需要 Wi-Fi 或蜂窝数据且必须在module.json5中声明ohos.permission.INTERNET权限。Q如何请求 HTTPS如何处理自签名证书Aohos.net.http默认支持 HTTPS会验证 CA 证书。自签名证书需要配置sslCertPath客户端证书或caPathCA 证书文件路径。开发阶段可以使用skipSSLVerification: true仅 debug 包。Q如何上传文件multipart/form-dataA设置Content-Type: multipart/form-data; boundaryxxx并手动构建 multipart 体或使用ohos.request.uploadFile模块专为文件上传优化。上一篇动画与过渡效果下一篇数据持久化Preferences