HttpRequest 文件下载示例编写
下面详细介绍创建该示例的步骤(确保 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:在 main_ability.cj 文件里添加如下的引用:
import ohos.ability.*
然后定义变量 globalContext:
var globalContext: Option
在 onCreate 函数里添加如下的代码:
globalContext = this.context
步骤 5:在 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.*
@Entry
@Component
class EntryView {
@State
var title: String = '仓颉版文件下载示例';
//连接、通讯历史记录
@State
var msgHistory: String = ''
//首页地址
@State
var downloadUrl: String = "http://...:8081/download?filename=demo.txt"
//登录地址
@State
var loginUrl: String = "http://...:8081/auth"
//用户名
@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() {
//http请求对象
let httpRequest = createHttp();
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 opt = HttpRequestOptions(
method: RequestMethod.GET,
header: header,
expectDataType: HttpDataType.ARRAY_BUFFER
)
httpRequest.request(this.downloadUrl, saveFileResponse, options: opt)
}
//下载文件请求的响应函数
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"
}
}
}
ckla.5000news.com
ckla.2500trip.com
ckla.htsyfs.com
ckla.hmgjjd.com
ckla.tcccpsb.com
ckla.hfsmttp.com
ckla.nnlianbao.com
ckla.xinchengabc.com
ckla.njns56.com
ckla.gzlcjzs.com
ckla.xinlvchuang.com
ckla.juanbanjicj.com
ckla.tongtaijituan.com
ckla.lydsmp.com
ckla.shinenergygroup.com
ckla.jingranchimian.com
ckla.tj-shengming.com
ckla.njxlkhs.com
ckla.shzljr.com
ckla.guanlinyouxuan.com
ckla.ynyoutu.com
ckla.jiadalong.com
ckla.jumeizi.com
ckla.zhs888.com
ckla.cnaoxin.com
ckla.afu365.com
ckla.tzhyex.com
ckla.xincaiit.com
ckla.senmaohuanbao.com
ckla.bjqunlemuye.com
ckla.lxtxqh.com
ckla.yuchentimes.com
ckla.hebeihongqi.com
ckla.ssyhmma.com
ckla.hyl98.com
ckla.youhezhixuan.com
ckla.jilinsport.com
ckla.wychyq.com
ckla.gdhrgk.com
ckla.jzha101.com
ckla.lutuohb.com
ckla.sgxinfeng.com
ckla.bjyongxuan.com
ckla.jxtrfund.com
ckla.fyjyzsgs.com
ckla.zgygzl.com
ckla.clwzycgp.com
ckla.wencfcw.com
ckla.zmuoo.com
ckla.xphysc.com
ckla.kalilan.com
ckla.jiexinlong.com
ckla.shiyongsh.com
ckla.myjhedu.com
ckla.xczipper.com
ckla.yjlzk.com
ckla.huangpihushuichan.com
ckla.yifanyuanyang.com
ckla.dianyunzhisheng.com
ckla.jx-tq.com
ckla.shenshiapp.com
ckla.hxjweiyu.com
ckla.gjmsxy.com
ckla.zgmcpj.com
ckla.tiquality.com
ckla.toto58.com
ckla.lhcgzj.com
ckla.gdlddb.com
ckla.volanswing.com
ckla.smxbsbl.com
ckla.hflxzsgc.com
ckla.nxttyq.com
ckla.jiamuli.com
ckla.banchendb.com
ckla.aguailuo.com
ckla.gzhajd.com
ckla.gzxuezhe.com
ckla.zywl9780bq.com
ckla.nc-lianshun.com
ckla.sp0557.com
步骤 6:编译运行,可以使用模拟器或者真机。
步骤 7:按照本节第 2 部分“HttpRequest 文件下载演示”操作即可。
- 代码分析
仓颉语言和 ArkTS 毕竟是两种语言,而且在目前阶段,仓颉语言对鸿蒙系统的适配暂时没有 ArkTS 完善,所以,有些 ArkTS 能比较方便使用的方法,在仓颉语言这里可能要适当调整下才能使用,比如获取上下文的函数 getContext,在 ArkTS 里,直接即可即可,而在仓颉语言里,需要先在 main_ability.cj 定义全局变量 globalContext,再从 onCreate 时间处理函数里对其进行赋值,然后再在需要的地方使用。
另外,仓颉版本中,服务端返回的 cookie 信息在当前的 API 中,位于 HttpResponse 类的 setCookie 属性中,并不在 header 属性中,这一点和 ArkTS 也不相同,以后可能会变化。
(本文作者原创,除非明确授权禁止转载)
本文源码地址:
https://gitee.com/zl3624/harmonyos_network_samples/tree/master/code/http/FileDownload4Cj
本系列源码地址:
https://gitee.com/zl3624/harmonyos_network_samples
标签:HttpRequest,示例,43,width,fontSize,let,100,ckla,com From: https://www.cnblogs.com/bkbk123/p/18538628