需求:加載驗(yàn)證碼;1.下載驗(yàn)證碼圖像文件;2.獲取header里面驗(yàn)證碼ID
踩坑--踩坑--踩坑
根據(jù)文檔使用 request.downloadFile 請(qǐng)求,官方示例:
// pages/xxx.ets
// 將網(wǎng)絡(luò)資源文件下載到應(yīng)用文件目錄并讀取一段內(nèi)容
import common from '@ohos.app.ability.common';
import fs from '@ohos.file.fs';
import request from '@ohos.request';
// 獲取應(yīng)用文件路徑
let context = getContext(this) as common.UIAbilityContext;
let filesDir = context.filesDir;
try {
request.downloadFile(context, {
url: 'https://xxxx/xxxx.txt',
filePath: filesDir + '/xxxx.txt'
}).then((downloadTask) = > {
downloadTask.on('complete', () = > {
console.info('download complete');
let file = fs.openSync(filesDir + '/xxxx.txt', fs.OpenMode.READ_WRITE);
let buf = new ArrayBuffer(1024);
let readLen = fs.readSync(file.fd, buf);
console.info(`The content of file: ${String.fromCharCode.apply(null, new Uint8Array(buf.slice(0, readLen)))}`);
fs.closeSync(file);
})
}).catch((err) = > {
console.error(`Invoke downloadTask failed, code is ${err.code}, message is ${err.message}`);
});
} catch (err) {
console.error(`Invoke downloadFile failed, code is ${err.code}, message is ${err.message}`);
}復(fù)制
里面存在一個(gè)解決不到的問(wèn)題是,獲取不到header里面驗(yàn)證碼ID,downloadTask 無(wú)法獲取....只能換常規(guī)方法獲取了。
換 httpRequest.request 來(lái)請(qǐng)求,示例代碼如下:
/**
* 下載文件(驗(yàn)證碼使用)
*/
static httpFileDownload(url: string, params?: any): Promise< ResponseResultJson > {
LogUtils.i("下載文件URL:" + url + "n請(qǐng)求參數(shù):" + (params != undefined ? "n請(qǐng)求參數(shù):" + JSON.stringify(params) : "無(wú)參數(shù)"));
//
let httpRequest = http.createHttp();
httpRequest.on('headersReceive', (header) = > {
//用于訂閱HTTP響應(yīng)頭,此接口會(huì)比request請(qǐng)求先返回。可以根據(jù)業(yè)務(wù)需要訂閱此消息
});
//
let responseResult = httpRequest.request(url, {
method: http.RequestMethod.GET,
readTimeout: RequestConstants.readTimeout,
connectTimeout: RequestConstants.connectTimeout,
header: {
'Content-Type': ContentType.JSON
},
expectDataType: http.HttpDataType.ARRAY_BUFFER, // 可選,指定返回?cái)?shù)據(jù)的類(lèi)型
extraData: params
});
let responseResultJson = new ResponseResultJson();
return responseResult.then(async (responseResult: http.HttpResponse) = > {
LogUtils.i("文件下載請(qǐng)求響應(yīng)URL:" + url + "n響應(yīng)結(jié)果:" + "n" + JSON.stringify(responseResult));
if (responseResult.responseCode === ResponseConstants.RESPONSE_SUCCESS) {
let header = responseResult.header
LogUtils.i('解析響應(yīng) header n' + JSON.stringify(header));
let headerJson = JSON.stringify(header)
let headerObj = JSON.parse(headerJson)
let sessionId = headerObj.sessionid as string
let serverModel = headerObj.servermodel as string
let encryptType = headerObj.encrypttype as string
//保存 header
await AppHelper.commitSessionId(sessionId);
await AppHelper.commitServerModel(serverModel);
await AppHelper.commitEncryptType(encryptType);
//解析文件
let result = responseResult.result as ArrayBuffer
// let filePath = FileConstants.rootFile + "/verifyCode_" + TimeExUtils.getNowYMDHMS1() + '.jpg'
let isHave = fs.accessSync(FileConstants.pathFile) //檢查文件目錄是否存在
if (!isHave) fs.mkdirSync(FileConstants.pathFile) //創(chuàng)建目錄
//
let filePath = FileConstants.pathFile + "verifyCode_" + TimeExUtils.getNowYMDHMS1() + '.jpg'
let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
fs.writeSync(file.fd, result); //將數(shù)據(jù)寫(xiě)入文件
fs.closeSync(file); //關(guān)閉文件
//
LogUtils.i("保存文件成功:n" + filePath + "t" + await FileUtils.getPathSize(filePath));
//結(jié)果
responseResultJson.code = ResponseConstants.CODE_SUCCESS
responseResultJson.isSuccess = true
responseResultJson.status = responseResult.responseCode
responseResultJson.serverModel = serverModel
responseResultJson.filePath = filePath
} else {
responseResultJson.code = ResponseConstants.CODE_ERROR;
responseResultJson.message = "業(yè)務(wù)異常:" + JSON.stringify(responseResult)
responseResultJson.isSuccess = false
}
return responseResultJson;
}).catch((error) = > {
LogUtils.i("文件下載請(qǐng)求響應(yīng)URL:" + url + "n請(qǐng)求異常:n" + JSON.stringify(error))
responseResultJson.code = ResponseConstants.CODE_ERROR;
responseResultJson.message = "請(qǐng)求異常:n" + JSON.stringify(error)
responseResultJson.isSuccess = false
return responseResultJson;
});
}復(fù)制
里面無(wú)用工具類(lèi)可以不用在意...里面獲取header可以有2種方法
鴻蒙OS開(kāi)發(fā) | 更多內(nèi)容↓點(diǎn)擊 | HarmonyOS與OpenHarmony技術(shù) |
---|---|---|
鴻蒙技術(shù)文檔 | 開(kāi)發(fā)知識(shí)更新庫(kù)gitee.com/li-shizhen-skin/harmony-os/blob/master/README.md 在這。 | 或+mau123789學(xué)習(xí),是v喔 |
方法一:
資料拿取+mau123789是v喔
httpRequest.on('headersReceive', (header) = > {
//用于訂閱HTTP響應(yīng)頭,此接口會(huì)比request請(qǐng)求先返回。可以根據(jù)業(yè)務(wù)需要訂閱此消息
});
方法二:
let header = responseResult.header
LogUtils.i('解析響應(yīng) header n' + JSON.stringify(header));
let headerJson = JSON.stringify(header)
let headerObj = JSON.parse(headerJson)
let sessionId = headerObj.sessionid as string
let serverModel = headerObj.servermodel as string
let encryptType = headerObj.encrypttype as string
獲取的值是一樣的。
獲取驗(yàn)證碼文件關(guān)鍵代碼:
1.參數(shù)里面的 expectDataType 需要設(shè)置為 http.HttpDataType.ARRAY_BUFFER;
- 結(jié)果轉(zhuǎn)換為ArrayBuffer,let result = responseResult.result as ArrayBuffer
運(yùn)行日志:
運(yùn)行效果:
完畢啦!!!! 驗(yàn)證碼獲取成功了!!!!
審核編輯 黃宇
-
HarmonyOS
+關(guān)注
關(guān)注
79文章
1967瀏覽量
30020 -
OpenHarmony
+關(guān)注
關(guān)注
25文章
3660瀏覽量
16158 -
鴻蒙OS
+關(guān)注
關(guān)注
0文章
188瀏覽量
4369
發(fā)布評(píng)論請(qǐng)先 登錄
相關(guān)推薦
評(píng)論