|
步骤1:HTTP网络请求需要申请ohos.permission.INTERNET权限,需要在配置文件module.json5中添加权限
"requestPermissions": [
{
"name": "ohos.permission.INTERNET",
"usedScene": {
"when": "always"
}
}
],
"module": {
"name": "entry",
"type": "entry",
"description": "$string:module_desc",
"mainElement": "EntryAbility",
"deviceTypes": [
"phone",
"tablet"
],
"requestPermissions": [
{
"name": "ohos.permission.INTERNET"
}
],
"deliveryWithInstall": true,
"installationFree": false,
步骤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<Response>{
//定义一个后台请求的基地址
const BASE_URL = "http://localhost:5228";
//创建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<Response>{
//定义一个后台请求的基地址
const BASE_URL = "http://localhost:5228";
//创建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;
}
============================
Response.ets
export default class Response {
/**
* 响应码
*/
code:number
/**
* 响应消息
*/
message:string
/**
* 响应数据
*/
data:any
success:string
}
步骤3:在ets文件中调用方法,由于封装getHttpData时为async方法,所以调用同样需要使用async方式,代码如下所示:
Button($r('app.string.login'))
.fontColor('#FFF')
.fontWeight(FontWeight.Bolder)
.width('50%')
//注意这里箭头函数 async
.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));
})
}
|
|