1.在使用ArkTS开发HarmonyOS应用时,需要调用HTTP网络请求 @ohos.net.http 动态获取数据,进行UI列表刷新,这想必是应用开发最常见的功能。但是根据官网网络请求的示例代码进行功能开发时,封装方法进行HTTP请求后,返回获取数据总是为空,无法返回调用接口获取的结果,经过一系列步骤检查,终于获取到数据,在此附上我的开发步骤、一些注意事项以及参考文档。
【开发步骤】
步骤1:根据官方文档,HTTP网络请求需要申请ohos.permission.INTERNET权限,需要在配置文件module.json5中添加权限,如下:
"requestPermissions"
: [
{
"name"
:
"ohos.permission.INTERNET"
,
"usedScene"
: {
"when"
:
"always"
}
}
]
步骤2:封装HTTP请求方法,由于这里需要请求数据后返回,所以不能直接用callback方式作为异步方法,需要使用Promise方式作为异步方法,配合await和async使用,代码参考如下
import http from '@ohos.net.http';
import Response from './Response';
import hilog from '@ohos.hilog';
export function requestPost(url:string,data?:any):Promise{
//定义一个后台请求的基地址
const BASE_URL = "http://192.168.17.1:9988";
//创建http
let httpRequest=http.createHttp();
let responseResult= httpRequest.request(BASE_URL+url,{
method:http.RequestMethod.POST,
header:{
'Content-Type': 'application/json'
},
extraData:JSON.stringify(data)
});
let response = new Response();
responseResult.then((value:http.HttpResponse)=>{
if (value.responseCode===200) {
hilog.info(0xFF00, '登录接口请求返回数据=========', '%{public}s 登录接口请求返回数据', JSON.stringify(value));
let res: Response = JSON.parse(`${value.result}`);
response.data = res.data;
response.code = res.code;
response.message = res.message;
}else{
response.message = '请求错误';
response.code = 400;
hilog.info(0xFF00, '登录接口请求错误=========', '%{public}s 登录接口请求错误', JSON.stringify(value));
}
return response;
}).catch(()=>{
response.message = '请求出错';
response.code = 400;
return response;
});
return;
};
export async function requestGet(url:string,data?:any):Promise{
//定义一个后台请求的基地址
const BASE_URL = "http://192.168.17.1:9988";
//创建http
let httpRequest=http.createHttp();
let responseResult= httpRequest.request(BASE_URL+url,{
method:http.RequestMethod.GET,
header:{
'Content-Type': 'application/json'
}
});
let response = new Response();
await responseResult.then((value)=>{
hilog.info(0xFF00, '登录接口请求返回数据=========', '%{public}s 登录接口请求返回数据', JSON.stringify(value));
let res: Response = JSON.parse(`${value.result}`);
response.data = res.data;
response.code = res.code;
response.message = res.message;
},(err)=>{
response.message = '请求错误';
response.code = 400;
hilog.info(0xFF00, '登录接口请求错误=========', '%{public}s 登录接口请求错误', JSON.stringify(err));
return response;
});
hilog.info(0xFF00, '登录接口成功返回的对象response=========', '%{public}s 登录接口成功返回的对象response', JSON.stringify(response));
return response;
}
步骤3:在ets文件中调用方法获取数据,注意由于封装getHttpData时为async方法,所以调用同样需要使用async方式调用,代码如下所示:
Button($r('app.string.login'))
.fontColor('#FFF')
.fontWeight(FontWeight.Bolder)
.width('50%')
.onClick(async () => {
let response:Response= await requestGet('/login',http.RequestMethod.GET);
hilog.info(0xFF00, '登录接口成功准备跳转页面=========', '%{public}s 登录接口成功准备跳转页面', response);
if (response.code===200) {
router.pushUrl({
url:'pages/HXIndex'
},(err)=>{
hilog.info(0xFF00, '跳转页面出错=========', '%{public}s 跳转页面出错', JSON.stringify(err));
})
}
【注意事项】
1、使用ArkTS中网络请求接口时,一定要申请ohos.permission.INTERNET权限;
2、封装方法进行HTTP请求时,注意需要使用Promise方式配合await和async使用,await添加到获取数据处理数据那一步,才能同步返回获取后数据结果;
3、调用HTTP请求方法时,同样需要使用async。
4、我提供的示例中未使用extraData,若需要进行参数请求时,注意不能对extraData整个参数进行加密处理,因为extraData通过string方式传递时,是使用key1=value1&key2=value2方式连接,其中“=”和“&”不能进行加密处理,只能加密处理其中的key或者value值。