仓颉应用开发之——网络访问(20)

一 概述

  • 应用隐私保护
  • ohos.net.http网络请求介绍
  • ohos.net.http网络访问示例

二 应用隐私保护

2.1 应用隐私说明

  • 同Android、iOS手机类型,涉及隐私权限访问时要实现声明并争得用户同意
  • 仓颉应用的隐私权限声明位于module.json5module下的"requestPermissions":[]
  • 该权限包含name(权限名)、reason(原因)、usedScene(场景)、when(何时)组成的json,name必须,其他可省略

2.2 示例(相机权限)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// module.json5
{
"module" : {
...
"requestPermissions":[
{
"name" : "ohos.permission.CAMERA",
"reason": "$string:camera_reason",
"usedScene": {
"abilities": [
"EntryAbility"
],
"when":"inuse"
}
},...
]
}
}

ohos.net.http网络请求介绍

3.1 网络请求过程

  1. 导入网络请求模块import ohos.net.http.*
  2. 创建httpRequest,执行HTTP请求任务
  3. httpRequest.onHeadersReceive({header: })设置HTTP响应头
  4. HttpRequestOptions(method:RequestMethod.POST,header)设置请求Option
  5. httpRequest.request()发送网络请求并解析

3.2 常见类或方法

No 类或方法 说明
1 func createHttp() 创建一个HTTP请求
2 class HttpRequest 执行HTTP请求任务
3 destroy() 中断请求任务

ohos.net.http网络访问示例

API接口:https://wanandroid.com/popular/column/json

4.1 module.json5添加访问权限

1
2
3
4
5
"requestPermissions": [
{
"name": "ohos.permission.INTERNET"
}
]

4.2 实体类封装(PopularBean)

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
package ohos_app_cangjie_entry.bean
import serialization.serialization.*
import std.math.*
import encoding.json.*
import std.collection.*

public class PopularBean <:Serializable<PopularBean> {


public var errorCode:Int64 = 0
public var errorMsg:String = ""
public var data: Option<Array<PopularData>> = Option<Array<PopularData>>.None

public func serialize(): DataModel {
return DataModelStruct()
.add(field<Option<Array<PopularData>>>("data", data))
.add(field<Int64>("errorCode", errorCode))
.add(field<String>("errorMsg", errorMsg))
}

public static func deserialize(dm: DataModel): PopularBean {
var dms = match (dm) {
case data: DataModelStruct => data
case _ => throw Exception("this data is not DataModelStruct")
}
var result = PopularBean()
result.data = Option<Array<PopularData>>.deserialize(dms.get("data"))
result.errorCode = Int64.deserialize(dms.get("errorCode"))
result.errorMsg = String.deserialize(dms.get("errorMsg"))

return result
}


}
public class PopularData <:Serializable<PopularData> {

public var chapterId:Int64 = 0
public var chapterName:String = ""
public var columnId:Int64 = 0
public var id:Int64 = 0
public var name: String = ""
public var subChapterId:Int64 = 0
public var subChapterName:String = ""
public var url:String = ""
public var userId:Int64 = 0

public func serialize(): DataModel {
return DataModelStruct()
.add(field<Int64>("chapterId", chapterId))
.add(field<String>("chapterName", chapterName))
.add(field<Int64>("columnId", columnId))
.add(field<Int64>("id", id))
.add(field<String>("name", name))
.add(field<Int64>("subChapterId", subChapterId))
.add(field<String>("subChapterName", subChapterName))
.add(field<String>("url", url))
.add(field<Int64>("userId", userId))

}

public static func deserialize(dm: DataModel): PopularData {
var dms = match (dm) {
case data: DataModelStruct => data
case _ => throw Exception("this data is not DataModelStruct")
}
var result = PopularData()
result.chapterId = Int64.deserialize(dms.get("chapterId"))
result.chapterName = String.deserialize(dms.get("chapterName"))
result.columnId = Int64.deserialize(dms.get("columnId"))
result.id = Int64.deserialize(dms.get("id"))
result.name = String.deserialize(dms.get("name"))
result.subChapterId = Int64.deserialize(dms.get("subChapterId"))
result.subChapterName = String.deserialize(dms.get("subChapterName"))
result.url = String.deserialize(dms.get("url"))
result.userId = Int64.deserialize(dms.get("userId"))
return result
}
}

4.3 API接口

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
package ohos_app_cangjie_entry.api
import ohos.net.http.*
import ohos.base.*
import std.collection.*
import ohos_app_cangjie_entry.bean.*
import ohos.hilog.*
import std.time.*
import std.sync.*
import ohos.state_manage.*
let mtx = ReentrantMutex()

public class APiRequest {
let baseURL = 'https://www.wanandroid.com/'
let httpRequest = createHttp();
var responseResult = ResponseResult()
var isRequestFinish = AtomicBool(false)

public func request():ResponseResult{
let option = HttpRequestOptions(
method: RequestMethod.GET, // 可选,默认为http.RequestMethod.GET
expectDataType: HttpDataType.STRING, // 可选,指定返回数据的类型
usingCache: true, // 可选,默认为true
priority: 1, // 可选,默认为1
// 开发者根据自身业务需要添加header字段
header: HashMap<String, String>([("content-type", "application/json")]),
readTimeout: 60000, // 可选,默认为60000ms
connectTimeout: 60000, // 可选,默认为60000ms
usingProtocol: HttpProtocol.HTTP1_1, // 可选,协议类型默认值由系统自动指定
usingProxy: UsingProxy.USE_DEFAULT, //可选,默认不使用网络代理,自API 10开始支持该属性
)

try {
// Hilog.info(0, "test", "resp===: 开始请求")
//https://wanandroid.com/harmony/index/json
//https://wanandroid.com/popular/column/json
httpRequest.request('https://wanandroid.com/popular/column/json', {err, resp =>
if (let Some(e) <- err) {
Hilog.error(0, "test","exception: ${e.message}")
this.responseResult.errorCode = 400
this.responseResult.errorMsg = e.message
this.responseResult.data = ""
}
if (let Some(r) <- resp) {
Hilog.info(0, "test", "resp===: ${r.result}")
//r.responseCode
this.responseResult.errorCode = 200
this.responseResult.errorMsg = "请求成功"
this.responseResult.data = r.result.toString()

} else {
Hilog.error(0, "test", "response is none")
this.responseResult.errorCode = 400
this.responseResult.errorMsg = "response is none"
this.responseResult.data = ""
}}, options: option)
sleep(Duration.second * 1)
//Hilog.info(0, "test", "resp===: 结束请求")
return responseResult
}catch (exception:Exception) {
this.responseResult.errorCode = 400
this.responseResult.errorMsg = "${exception.message}"
this.responseResult.data = "出错了"
return responseResult
}finally {
//sleep(Duration.second * 1)
//return responseResult
}
}
}

4.4 UI中调用接口

1
2
3
4
5
6
7
8
9
10
11
protected override func onPageShow() {

var requestResult = APiRequest().request()
Hilog.printInfo("printInfo","${requestResult.data}")

var jve:JsonValue = JsonValue.fromStr(requestResult.data)
var dml = DataModel.fromJson(jve)
Hilog.printInfo("printInfo","harmony=${dml.toJson()}")
var popularData:PopularBean = PopularBean.deserialize(dml)

}

五 参考