一、鸿蒙http数据请求
1.1 基本概念
开发的应用可以通过系统内置的 http 模块,通过 HTTP 协议和服务器进行通讯
什么是服务器?
在网络上提供服务器的一台电脑,比如提供数据服务
什么是 http 模块?
鸿蒙内置的一个模块,可以通过 【HTTP 协议】和服务器进行通信
3.HTTP协议?
1
| 在通讯的时候需要按照格式发送内容,才可以进行通讯
|
1.2 基本使用
1 2 3 4 5 6 7 8 9 10
| // 1. 导入 import http from '@ohos.net.http';
// 2. 创建请求对象 const req = http.createHttp() // 3. 根据提供好的 地址发送请求,并在 then 中获取服务器响应的内容 req.request('请求地址') .then((res: http.HttpResponse) => { AlertDialog.show({ message: JSON.stringify(res) }) })
|
配置网络权限
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
| { "module": { "name": "entry", "type": "entry", "description": "$string:module_desc", "mainElement": "EntryAbility", "deviceTypes": [ "phone", "tablet", "2in1" ], "deliveryWithInstall": true, "installationFree": false, "pages": "$profile:main_pages",
/****需要在该处添加网络配置权限*****/ "requestPermissions": [ { "name": "ohos.permission.INTERNET" }
], "abilities": [ { "name": "EntryAbility", "srcEntry": "./ets/entryability/EntryAbility.ets", "description": "$string:EntryAbility_desc", "icon": "$media:layered_image", "label": "$string:EntryAbility_label", "startWindowIcon": "$media:startIcon", "startWindowBackground": "$color:start_window_background", "exported": true, "skills": [ { "entities": [ "entity.system.home" ], "actions": [ "action.system.home" ] } ] } ] } }
|
二、URL的认识
2.1 概念
URL 的组成
URL 无非就是一个给定的独特资源在 Web 上的地址。理论上说,每个有效的 URL 都指向一个唯一的资源。这个资源可以是一个 HTML 页面,一个 CSS 文档,一幅图像,等等。
2.2 URL参数查询
URL查询参数是提供给网络服务器的额外参数。这些参数是用 & 符号分隔的键/值对列表。
目的:让我们获取到指定需求的数据!!!
案例:获取n条笑话
参数: num 笑话数量 ** req.request(**https://api-vue-base.itheima.net/api/joke/list?num=${this.jokeNum}
)
三、开心一笑
- 默认获取若干条笑话,并渲染到页面上
- 下拉刷新
- 触底加载更多
- 点击返回顶部

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
| import http from '@ohos.net.http'
// 创建请求对象 const req = http.createHttp()
interface JokeRes { msg: string code: number data: string[] }
@Entry @Component struct Day01_07_Jokes { @State jokes: string [] = [] jokeNum: number = 5 @State refreshing: boolean = false listScroller: Scroller = new Scroller() isLoadingMore: boolean = false
getJokeList() { req.request('https://api-vue-base.itheima.net/api/joke/list?num=' + this.jokeNum) .then((res: http.HttpResponse) => { // AlertDialog.show({ // message: res.result.toString() // }) const Res = JSON.parse(res.result as string) as JokeRes this.jokes = Res.data this.refreshing = false }) }
aboutToAppear(): void { this.getJokeList() }
build() { Refresh({ refreshing: $$this.refreshing }) { Column() { // 顶部 this.HeaderBuilder() // 笑话列表 List({ space: 10, scroller: this.listScroller }) { ForEach(this.jokes, (joke: string) => { ListItem() { Column({ space: 10 }) { Text(joke.split(',')[0]) .fontSize(20) .fontWeight(600)
Row({ space: 15 }) { titleIcon({ icon: $r('app.media.ic_public_time'), info: '2024-1-1' }) titleIcon({ icon: $r('app.media.ic_public_read'), info: '阅读(6666)' }) titleIcon({ icon: $r('app.media.ic_public_comments'), info: '评论(123)' }) }
Text(joke) .fontSize(15) .fontColor(Color.Gray) } .width('100%') .alignItems(HorizontalAlign.Start) .padding(20)
} .borderRadius(10) .backgroundColor(Color.White) .shadow({ radius: 2, color: Color.Gray }) }) ListItem() { LoadingProgress() .width(40) }.width('100%') } .padding(10) .layoutWeight(1) .onReachEnd(() => { if (!this.isLoadingMore) { this.isLoadingMore = true // AlertDialog.show({ // message: 'hello world' // }) req.request('https://api-vue-base.itheima.net/api/joke/list?num=' + this.jokeNum) .then((res: http.HttpResponse) => { const response = JSON.parse(res.result as string) as JokeRes this.jokes.push(...response.data) //展开运算符 this.isLoadingMore = false }) } }) } .width('100%') .height('100%') .backgroundColor('#f6f6f6') } .onRefreshing(() => { this.getJokeList() }) }
@Builder HeaderBuilder() { Row() { Image($r('app.media.ic_public_drawer_filled')) .width(25);
Image($r('app.media.ic_public_joke_logo')) .width(30) .onClick(() => { this.listScroller.scrollTo({ xOffset: 0, yOffset: 0, animation: true }) }) Image($r('app.media.ic_public_search')) .width(30); } .width('100%') .justifyContent(FlexAlign.SpaceBetween) .height(60) .padding(10) .border({ width: { bottom: 2 }, color: '#f0f0f0' }) .backgroundColor(Color.White) } }
@Component struct titleIcon { icon: ResourceStr = '' info: string = ''
build() { Row() { Image(this.icon) .width(15) .fillColor(Color.Gray) Text(this.info) .fontSize(14) .fontColor(Color.Gray) } } }
|
四、 请求方法和数据提交
GET — 获取数据
POST — 提交数据
PUT — 修改数据(全部)
DELETE — 删除数据
PATCH — 修改数据(部分)
上面开心一笑案例属于(GET)获取数据这一请求方法
日常开发中较为常见的需要提交数据给服务器的场景(POST):用户登录,在线买东西。
提交数据基本写法:
1 2 3 4 5 6 7
| const req = http.createHttp() req.request('请求地址', { method: http.RequestMethod.POST, // 通过枚举的方式设置请求方法,如果是 get 可以省略 extraData: {} // 数据写在 extraData 中 支持 对象 字符串 ArrayBuffer(二进制数据) extraData:'key=value&key2=value2'// 字符串的话 写成 'key=value&key2=value2'.... // 对象的话需要额外设置其他参数,先用 })
|
4.1 请求报文
请求报文:浏览器按照HTTP协议要求的格式,发送给服务器的内容
请求报文的组成部分:
1.请求行:请求方法,URL,协议(第一行)
2.请求头:以键值对的格式携带的附加信息,比如:Content-Type(第二行开始到空行)
3.空行:分隔请求头,空行之后的是发送给服务器的资源(空行)
4.请求体:发送的资源(空行之后)
4.2 响应报文
服务器按照HTTP协议要求的格式,返回给浏览器的内容
- 响应行(状态行):协议、HTTP响应状态码、状态信息(第一行)
- 响应头:以键值对的格式携带的附加信息,比如:Content-Type(第一行到空行)
- 空行:分隔响应头,空行之后的是服务器返回的资源(空行)
- 响应体:返回的资源(空行之后)
五、我的书架
请求参数(2种):Query 1.查询参数 ?key = value& key = value
完整代码:AndyLucky/鸿蒙NEXT我的书架
书架可以通过网络请求到服务器添加自己喜欢的书籍以及修改 新增 删除