1. Request部件简介

鸿蒙系统提供了上传下载部件,即Request部件,封装了上传下载能力,方便了相关功能的开发。不过,在当前适配仓颉语言的Request部件中,只提供了基于代理(Agent)的上传下载能力,方便性也相对ArkTS语言差一些,毕竟是刚开始适配,以后应该会提供更丰富的功能。本文将使用仓颉语言基于Request部件实现文件下载功能,下载文件的服务端也是本系列第12篇文章《鸿蒙网络编程系列12-使用Request部件下载文件到本地示例》中使用的服务端,该服务端需要登录后才可以下载,本文也复用了本系列第41篇文章《鸿蒙网络编程系列41-仓颉版HttpRequest模拟登录示例》中演示的模拟登录能力,在获取登录后的cookie后,把该cookie做为Request部件首部的一部分,做为服务端允许下载的凭据。

2. Request部件下载演示

本示例运行后的页面如图所示:

输入用户名、密码,然后输入服务端登录地址,单击“登录”按钮即可进行登录,如图所示:

登录成功后,输入下载文件的地址以及本地文件名称,单击“下载”按钮即可进行下载,如图所示:

下载完毕后,还输出了文件的内容。

3. Request部件下载示例编写

下面详细介绍创建该示例的步骤(确保DevEco Studio已安装仓颉插件)。

步骤1:创建[Cangjie]Empty Ability项目。

步骤2:在module.json5配置文件加上对权限的声明:

"requestPermissions": [
      {
        "name": "ohos.permission.INTERNET"
      }
    ]

这里添加了访问互联网的权限。

步骤3:在build-profile.json5配置文件加上仓颉编译架构:

"cangjieOptions": {
      "path": "./src/main/cangjie/cjpm.toml",
      "abiFilters": ["arm64-v8a", "x86_64"]
    }

步骤4:在index.cj文件里添加如下的代码:

package ohos_app_cangjie_entry

import ohos.base.*
import ohos.component.*
import ohos.state_manage.*
import ohos.state_macro_manage.*
import std.collection.HashMap
import ohos.net.http.*
import ohos.file_picker.*
import ohos.ability.getStageContext
import ohos.ability.*
import ohos.file_fs.*
import ohos.request.agent.*
import ohos.request.agent.Progress as agentProgress

@Entry
@Component
class EntryView {
    @State
    var title: String = '仓颉版Request部件下载示例';
    //连接、通讯历史记录
    @State
    var msgHistory: String = ''
    //首页地址
    @State
    var downloadUrl: String = ""
    //登录地址
    @State
    var loginUrl: String = ""
    //用户名
    @State
    var loginName: String = "zhanglei"
    //密码
    @State
    var passwd: String = "HarmonyOS"

    @State
    //保存到的本地文件名称
    var localFileName: String = "demo.txt"
    //cookie中传递的sessionid
    var sessionId: String = ""
    let scroller: Scroller = Scroller()

    func build() {
        Row {
            Column {
                Text(title).fontSize(14).fontWeight(FontWeight.Bold).width(100.percent).textAlign(TextAlign.Center).
                    padding(10)

                Flex(FlexParams(justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center)) {
                    Text("用户名:").fontSize(14)

                    TextInput(text: loginName).onChange({
                        value => loginName = value
                    }).width(100).fontSize(11).flexGrow(1)

                    Text("密码:").fontSize(14)

                    TextInput(text: passwd).onChange({
                        value => passwd = value
                    }).width(100).fontSize(11).setType(InputType.Password).flexGrow(1)
                }.width(100.percent).padding(10)

                Flex(FlexParams(justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center)) {
                    Text("登录地址:").fontSize(14).width(80)

                    TextInput(text: loginUrl).onChange({
                        value => loginUrl = value
                    }).width(100).fontSize(11).flexGrow(1)

                    Button("登录").onClick {
                        evt => login()
                    }.width(70).fontSize(14).flexGrow(0)
                }.width(100.percent).padding(10)

                Flex(FlexParams(justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center)) {
                    Text("下载文件地址:").fontSize(14)

                    TextInput(text: downloadUrl).onChange({
                        value => downloadUrl = value
                    }).width(100).fontSize(11).flexGrow(1)
                }.width(100.percent).padding(10)

                Flex(FlexParams(justifyContent: FlexAlign.End, alignItems: ItemAlign.Center)) {
                    Text("本地文件名称:").fontSize(14)

                    TextInput(text: localFileName).onChange({
                        value => localFileName = value
                    }).width(100).fontSize(11).flexGrow(1)

                    Button("下载").onClick {
                        evt => downloadFile()
                    }.width(70).fontSize(14)
                }.width(100.percent).padding(10)

                Scroll(scroller) {
                    Text(msgHistory).textAlign(TextAlign.Start).padding(10).width(100.percent).backgroundColor(0xeeeeee)
                }.align(Alignment.Top).backgroundColor(0xeeeeee).height(300).flexGrow(1).scrollable(
                    ScrollDirection.Vertical).scrollBar(BarState.On).scrollBarWidth(20)
            }.width(100.percent).height(100.percent)
        }.height(100.percent)
    }

    //下载文件
    func downloadFile() {
        let header = HashMap<String, String>(
            ("Accept-Encoding", "gzip, deflate, br"),
            ("Cookie", 'sessionid=' + this.sessionId),
            ("User-Agent",
                "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36")
        );

        let localFilePath = globalContext.getOrThrow().filesDir + "/" + this.localFileName
        let config = Config(
            action: DOWNLOAD,
            url: downloadUrl,
            headers: header,
            saveas: localFilePath,
            overwrite: true
        )
        try {
            let task = create(getStageContext(globalContext.getOrThrow()), config)
            task.on("completed", CompletedCallback(this))

            task.start()
        } catch (e: BusinessException) {
            this.msgHistory += "下载文件异常:" + e.toString() + "\r\n"
        }
    }

    //在日志中显示指定信息
    func addMsgInfo(info: String) {
        this.msgHistory += info
    }

    //输出下载的文件内容
    func showDownloadFileInfo() {
        let localFilePath = globalContext.getOrThrow().filesDir + "/" + this.localFileName
        let content = FileFs.readText(localFilePath)
        msgHistory += "下载的文件内容:" + content + "\r\n"
    }

    //下载文件请求的响应函数
    func saveFileResponse(err: ?BusinessException, response: ?HttpResponse) {
        if (let Some(e) <- err) {
            msgHistory += "请求失败:" + e.message + "\r\n"
        }

        if (let Some(resp) <- response) {
            msgHistory += "响应码:${resp.responseCode.getValue()}\r\n"

            let localFilePath = globalContext.getOrThrow().filesDir + "/" + this.localFileName
            if (FileFs.access(localFilePath)) {
                FileFs.unlink(localFilePath)
            }
            match (resp.result) {
                case HttpData.ARRAY_DATA(value) =>
                    let file = FileFs.open(localFilePath, mode: CREATE.mode | READ_WRITE.mode)
                    FileFs.write(file.fd, value)
                    FileFs.close(file)

                    //输出文件内容
                    let content = FileFs.readText(localFilePath)
                    msgHistory += "文件内容${content}\r\n"
                case _ => msgHistory += "响应的数据不是二进制类型\r\n"
            }
        }
    }

    //登录
    func login() {
        //http请求对象
        let httpRequest = createHttp();
        //请求的登录名和密码参数
        let params = "username=" + loginName + "&password=" + passwd

        let header = HashMap<String, String>(("Content-Type", "application/x-www-form-urlencoded"));
        let opt = HttpRequestOptions(
            method: RequestMethod.POST,
            extraData: HttpData.STRING_DATA(params),
            header: header,
            expectDataType: HttpDataType.STRING
        )

        httpRequest.request(loginUrl, dealWithResponse, options: opt)
    }

    //登录的响应处理函数
    func dealWithResponse(err: ?BusinessException, response: ?HttpResponse) {
        if (let Some(e) <- err) {
            msgHistory += "请求失败:" + e.message + "\r\n"
        }

        if (let Some(resp) <- response) {
            msgHistory += "响应码:${resp.responseCode.getValue()}\r\n"

            var findResult = false
            //从setCookie列表中查找名称为sessionid的cookie对应的值
            for (setCookieItem in resp.setCookie) {
                let cookie = setCookieItem.split(";")
                for (cookieItem in cookie) {
                    let kvItem = cookieItem.split("=")
                    if (kvItem[0].trimAscii() == "sessionid") {
                        sessionId = kvItem[1]
                        findResult = true
                        break;
                    }
                }
                if (findResult) {
                    msgHistory += "sessionId = ${sessionId}\r\n"
                    break
                }
            }
        } else {
            msgHistory += "响应为空\r\n"
        }
    }
}

//下载完成的回调
class CompletedCallback <: Callback1Argument<agentProgress> {
    let parent: EntryView
    public init(parent: EntryView) {
        this.parent = parent
    }
    public open func invoke(progress: agentProgress): Unit {
        parent.addMsgInfo("下载完毕\r\n")
        parent.showDownloadFileInfo()
    }
}

步骤5:编译运行,可以使用模拟器或者真机。

步骤6:按照本文第2部分“Request部件下载演示”操作即可。

4. 代码分析

本示例的关键部分有三处,第一处是关于模拟登录获取sessionid,并且把cookie应用到Request部件的首部中,代码如下

let header = HashMap<String, String>(
            ("Accept-Encoding", "gzip, deflate, br"),
            ("Cookie", 'sessionid=' + this.sessionId),
            ("User-Agent",
                "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36")
        );

        let localFilePath = globalContext.getOrThrow().filesDir + "/" + this.localFileName
        let config = Config(
            action: DOWNLOAD,
            url: downloadUrl,
            headers: header,
            saveas: localFilePath,
            overwrite: true
        )

第二部分是关于下载任务的回调,这是和ArkTS语言示例差别较大的地方,该回调类需要实现Callback1Argument<agentProgress>接口,代码如下:

//下载完成的回调
class CompletedCallback <: Callback1Argument<agentProgress> {
    let parent: EntryView
    public init(parent: EntryView) {
        this.parent = parent
    }
    public open func invoke(progress: agentProgress): Unit {
        parent.addMsgInfo("下载完毕\r\n")
        parent.showDownloadFileInfo()
    }
}

第三部分是命名空间的问题,因为Callback1Argument接口包括一个Progress类型的参数,该类型和ohos.component.*命名空间的Progress类型有冲突,所以这里重命名为agentProgress类型,导入代码如下:

import ohos.request.agent.Progress as agentProgress

(本文作者原创,除非明确授权禁止转载)

本文源码地址:
https://gitee.com/zl3624/harmonyos_network_samples/tree/maste...

本系列源码地址:
https://gitee.com/zl3624/harmonyos_network_samples


长弓三石
1 声望0 粉丝