需求:加載驗證碼;1.下載驗證碼圖像文件;2.獲取header里面驗證碼ID
踩坑--踩坑--踩坑
根據(jù)文檔使用 request.downloadFile 請求,官方示例:
// pages/xxx.ets
// 將網(wǎng)絡資源文件下載到應用文件目錄并讀取一段內(nèi)容
import common from '@ohos.app.ability.common';
import fs from '@ohos.file.fs';
import request from '@ohos.request';
// 獲取應用文件路徑
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}`);
}復制
里面存在一個解決不到的問題是,獲取不到header里面驗證碼ID,downloadTask 無法獲取....只能換常規(guī)方法獲取了。
換 httpRequest.request 來請求,示例代碼如下:
/**
* 下載文件(驗證碼使用)
*/
static httpFileDownload(url: string, params?: any): Promise< ResponseResultJson > {
LogUtils.i("下載文件URL:" + url + "n請求參數(shù):" + (params != undefined ? "n請求參數(shù):" + JSON.stringify(params) : "無參數(shù)"));
//
let httpRequest = http.createHttp();
httpRequest.on('headersReceive', (header) = > {
//用于訂閱HTTP響應頭,此接口會比request請求先返回。可以根據(jù)業(yè)務需要訂閱此消息
});
//
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, // 可選,指定返回數(shù)據(jù)的類型
extraData: params
});
let responseResultJson = new ResponseResultJson();
return responseResult.then(async (responseResult: http.HttpResponse) = > {
LogUtils.i("文件下載請求響應URL:" + url + "n響應結果:" + "n" + JSON.stringify(responseResult));
if (responseResult.responseCode === ResponseConstants.RESPONSE_SUCCESS) {
let header = responseResult.header
LogUtils.i('解析響應 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ù)寫入文件
fs.closeSync(file); //關閉文件
//
LogUtils.i("保存文件成功:n" + filePath + "t" + await FileUtils.getPathSize(filePath));
//結果
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è)務異常:" + JSON.stringify(responseResult)
responseResultJson.isSuccess = false
}
return responseResultJson;
}).catch((error) = > {
LogUtils.i("文件下載請求響應URL:" + url + "n請求異常:n" + JSON.stringify(error))
responseResultJson.code = ResponseConstants.CODE_ERROR;
responseResultJson.message = "請求異常:n" + JSON.stringify(error)
responseResultJson.isSuccess = false
return responseResultJson;
});
}復制
里面無用工具類可以不用在意...里面獲取header可以有2種方法
鴻蒙OS開發(fā) | 更多內(nèi)容↓點擊 | HarmonyOS與OpenHarmony技術 |
---|---|---|
鴻蒙技術文檔 | 開發(fā)知識更新庫gitee.com/li-shizhen-skin/harmony-os/blob/master/README.md 在這。 | 或+mau123789學習,是v喔 |
方法一:
資料拿取+mau123789是v喔
httpRequest.on('headersReceive', (header) = > {
//用于訂閱HTTP響應頭,此接口會比request請求先返回??梢愿鶕?jù)業(yè)務需要訂閱此消息
});
方法二:
let header = responseResult.header
LogUtils.i('解析響應 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
獲取的值是一樣的。
獲取驗證碼文件關鍵代碼:
1.參數(shù)里面的 expectDataType 需要設置為 http.HttpDataType.ARRAY_BUFFER;
- 結果轉換為ArrayBuffer,let result = responseResult.result as ArrayBuffer
運行日志:
運行效果:
完畢啦?。。?! 驗證碼獲取成功了?。。?!
審核編輯 黃宇
-
HarmonyOS
+關注
關注
79文章
1975瀏覽量
30209 -
OpenHarmony
+關注
關注
25文章
3722瀏覽量
16323 -
鴻蒙OS
+關注
關注
0文章
188瀏覽量
4400
發(fā)布評論請先 登錄
相關推薦
評論