二十二、网络http请求、promise
网络请求需要添加网络访问权限:
在module.json5文件中添加。
"requestPermissions": [ { "name": "ohos.permission.INTERNET" } ]
开发步骤:
1. import 需要的http模块。
import http from '@ohos.net.http'
2. 创建一共HTTP请求,防护一个HttpRequest对象。
let httpReq = http.createHttp()
3. 订阅HTTP响应头。
4 . 根据URL地址,发起HTTP网络请求。
5. 处理HTTP相应头和HTTP网络请求的返回结果。
https://api.apiopen.top/api/sentences ---->随机诗词API
httpReq.request('https://api.apiopen.top/api/sentences',{ method:http.RequestMethod.GET }, (err,data) => { //4. 处理结果 if(!err){ let name = JSON.parse(`${data.result}`).result.name this.poem = name } })
案例代码:
// 1.导入http模块 import http from '@ohos.net.http' @Entry @Component struct HttpReq { @State poem: string = '把酒问青天' //生命周期函数 aboutToAppear(){ //2. 创建http请求对象 let httpReq = http.createHttp() //3. 发起请求 httpReq.request('https://api.apiopen.top/api/sentences',{ method:http.RequestMethod.GET }, (err,data) => { //4. 处理结果 if(!err){ let name = JSON.parse(`${data.result}`).result.name this.poem = name } }) } build() { Row() { Column() { Text(this.poem) .fontSize(50) .fontWeight(FontWeight.Bold) } .width('100%') } .height('100%') } }
Promise请求:
import http from '@ohos.net.http'; @Entry @Component struct HttpReqPromise { @State poem: string = '把酒问青天' @State from: string = '' //生命周期函数 aboutToAppear(){ let httpReq = http.createHttp() let promise = httpReq.request('https://api.apiopen.top/api/sentences') promise.then((data) => { this.poem = JSON.parse(`${data.result}`).result.name this.from = JSON.parse(`${data.result}`).result.from }).catch((err) => { console.log(err) }) } build() { Row() { Column() { Text(this.poem) .fontSize(20) .fontWeight(FontWeight.Bold) Text(this.from) .fontSize(20) .fontWeight(FontWeight.Bold) } .width('100%') } .height('100%') } }
分类:
HarmonyOS
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
2022-01-05 uni-app 唤醒调用第三方app并传参
2021-01-05 Git
2021-01-05 mybatis plus构造器
2021-01-05 String和StringBuffer的区别
2021-01-05 java编写简单的Socket通信应用 实现服务端同时处理多个客户端