设为首页收藏本站

恒泰软件,必属精品

 找回密码
 立即注册

QQ登录

只需一步,快速开始

搜索
热搜: 活动 交友 discuz
查看: 383|回复: 0
打印 上一主题 下一主题

ArkTS网络数据请求获取数据并处理

[复制链接]

190

主题

200

帖子

2907

积分

管理员

Rank: 9Rank: 9Rank: 9

积分
2907
跳转到指定楼层
楼主
发表于 2024-6-17 16:10:21 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
步骤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));
               })
             }


分享到:  !wechat_share!!wechat_share! QQ好友和群QQ好友和群 QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友
收藏收藏
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|Archiver|手机版|小黑屋|恒泰软件 ( 桂ICP备13003577号-1 )  

桂公网安备 45082102000255号

GMT+8, 2024-9-8 10:03 , Processed in 0.118417 second(s), 24 queries .

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表