鸿蒙ArkTS中的获取网络数据

**  一、通过web组件加载网页**

  在C/S应用程序中,都有网络组件用于加载网页,鸿蒙ArkTS中也有类似的组件。

  web组件,用于加载指定的网页,里面有很多的方法可以调用,虽然现在用得比较少,了解还是必须的。

  演示代码:

复制代码
import webview from '@ohos.web.webview';

@Entry
@Component
struct Index {
  myController:webview.WebviewController=new  webview.WebviewController() //控制器
  @State strWebURL:string=''  //网络地址
  @State strWebResult:string='' //返回的结果

  build() {
    Column({space:10}) {
      Row(){
        Column(){
          Row(){
            TextInput({placeholder:'请输入网址'}).layoutWeight(1).onChange((value:string)=>{this.strWebURL=value})
            Button('加载').onClick(()=>{
              // this.strWebURL = 'https://www.baidu.com';
              this.myController.loadUrl(this.strWebURL);
            })
            Button('刷新').onClick(()=>{
              this.myController.refresh();
            })
            Button('停止').onClick(()=>{
              this.myController.stop();
            })

          }
          Web({
            src:this.strWebURL,
            controller:this.myController
          }).height('100%').width('100%').zoomAccess(true).textZoomRatio(2)
        }
      }

    }.height('100%').width('100%')
  }
}

  我的计算机很卡顿,一直没有重装系统,可以运行出效果,安装了Huawei Mate10的真机模拟器。

  1、使用系统自带的模拟器Previewer预览时系统会提示:Property 'relativeOffset' does not exist on type 'TextAttribute'. <ArkTSCheck>,连上华为Mate10,下载安装文件后,模拟效果就出来了。

  2、需要开通网络访问权限。在module.json5中配置网络访问权限:

  3、注意函数名的大小写,我因为这个问题折腾了2个多小时,犯了很低级的错误。

复制代码
"module": {
  "requestPermissions": [
    {
      "name": "ohos.permission.INTERNET"
    }
  ]
}

**  二、加载本地的网页并执行网页中的函数并得到返回数据**

  与上面的类似,只是文件存放到resource\rawfile目录下。可以执行网页的程序并得到返回值。

复制代码
import webview from '@ohos.web.webview';

@Entry
@Component
struct Index {
  myController:webview.WebviewController=new  webview.WebviewController() //控制器
  @State strResult:string=''

  build() {
    Column({space:10}) {
          Row(){
                Web({
                  src:$rawfile('test.html'),
                  controller:this.myController
                }).height(300).width('100%').javaScriptAccess(true)
          }.height(300).width('100%').backgroundColor(Color.Pink)

          Row({space:6}){
              Button('加载本地网页').onClick(()=>{
                console.log('123')
                this.myController.runJavaScript('Test()').then(result =>{
                  console.log(result)
                  this.strResult=result})
                console.log(this.strResult)
              })
              Text('返回数据:')
              Text(this.strResult)
          }.height(200).width('100%').backgroundColor(Color.Orange)
    }.height('100%').width('100%')
  }
}

  效果图:

  网页test.html内容:

复制代码
<!DOCTYPE html>
<html>
<head>
    <title>JavaScript->函数</title>
</head>
<body>
  <div id="demo"><font size=32>JavaScript->函数</font></div>
  <input type="button" value="点击" onclick="Test123()" id="DD3"/>
  <input type="button" value="点击" onclick="Test()" id="DD3"/>
<script>
	function Test(){
		document.getElementById("demo").style.color="#d70008"
		return 'test.html返回的数据'
	}
	function Test123(){
		return '点击按钮l返回的数据'
	}
</script>
</body>
</html>

**  三、通过get和post获取网络数据**

使用http不可视组件可以通过get和post方法来获取网络数据,格式比较固定,实际使用时可以根据情况再封装一下,就是加上async和await。

代码:

复制代码
import http from '@ohos.net.http';
import { JSON } from '@kit.ArkTS';

@Entry
@Component
struct MyComponent {
  @State StrReturnData_Get:string=''
  @State StrReturnData_Post:string=''
  @State strUrl_Get:string=''
  @State strUrl_Post:string=''

  objectToStringEncoding(obj:Record<string,string>) {
  let encodedStr = '';
  for (let key of Object.entries(obj)) {
      encodedStr += `${key[0]}=${encodeURIComponent(key[1])}&`;
  }
  return encodedStr.slice(0, -1); // 去除最后多余的 '&'
}
  build() {
    Column({space:10}) {
      Row(){
        Button('获取Get数据').fontSize(12).onClick(() => this.getWeatherData());
        TextInput({placeholder:'请输入网址'}).onChange((value:string)=>{this.strUrl_Get=value})
      }.width('100%').height(32)
      Row(){
        Text(this.StrReturnData_Get)
      }.layoutWeight(1)
      Row(){
        Button('获取Post数据').fontSize(12).onClick(() => this.getPostData())
        TextInput({placeholder:'请输入网址'}).onChange((value:string)=>{this.strUrl_Post=value})
      }.width('100%').height(32)
      Row(){
        Text(this.StrReturnData_Post)
      }.layoutWeight(1)
    }
  }

  getWeatherData() {
        let httpRequest =http.createHttp()
        httpRequest.request(this.strUrl_Get,
                            {
                                method:http.RequestMethod.GET,
                                header:{'Content-Type':'application/json'},
                            },
                            (error,data)=>{
                                  if(!error){
                                    this.StrReturnData_Get=data.result.toString()
                                    console.log(this.StrReturnData_Get)
                                  }
                                  else {
                                    console.log(data.responseCode.toString())
                                    console.log(JSON.stringify(error))
                                  }
                            }
        )
  }

  getPostData() {
    let httpRequest =http.createHttp()
    httpRequest.request(this.strUrl_Post,
      {
        method:http.RequestMethod.POST,
        header:{'Content-Type':'application/x-www-form-urlencoded'},
        extraData:this.objectToStringEncoding(
          {"name":"张三"}
        )
        //   readTimeout:3000,
        // connectTimeout:3000
      },
      (error,data)=>{
        if(!error){
          this.StrReturnData_Post=data.result.toString()
          console.log(this.StrReturnData_Post)
        }
        else {
          console.log(data.responseCode.toString())
          console.log(JSON.stringify(error))
        }
      }
    )
  }
}

  效果:

  实际上,ArkTS中封装了很多获取网络数据的组件,后面再一一学习。

相关推荐
云端漫步19878 小时前
HarmonyOS 互动卡片实战:快递卡片与睡眠卡片完整开发流程
华为·harmonyos
智塑未来9 小时前
鸿蒙6.1隐私安心加倍:加密分享、星盾防诈、应用锁三重保护,守护到位
华为·harmonyos
byte轻骑兵9 小时前
2026手机远程办公:向日葵、TeamViewer、ToDesk鸿蒙适配+传文件+AI审计功能对比
智能手机·harmonyos·todesk·teamviewer·手机远程办公
贾伟康10 小时前
【知律|06】HarmonyOS ArkTS 法律分类实战:让民法、劳动、消费等入口可维护
harmonyos·arkts·arkui·分类设计·多设备
梦想不只是梦与想1 天前
鸿蒙 测试工具:DevEco Testing(一)
测试工具·harmonyos·testing
大锅盖11 天前
Web 工单要调用相机,第一步不是打开取景框,而是建立能力门禁
前端·数码相机·harmonyos
贾伟康1 天前
【华夏二十四节气|07】HarmonyOS 6.0.2(22) ArkTS 节气搜索实战:多字段匹配与四态闭环
移动开发·harmonyos·arkts·arkui·本地搜索
大龄秃头程序员1 天前
Flutter 项目鸿蒙适配实战:从环境搭建到多环境打包全指南
harmonyos
贾伟康1 天前
【万能转换器|18】HarmonyOS ArkTS 权限与隐私实战:让 module.json5、功能说明和拒绝路径一致
移动开发·harmonyos·arkts·权限管理·隐私合规
贾伟康1 天前
【万能转换器|19】HarmonyOS ArkTS 回归测试实战:覆盖启动、空数据、异常输入和重复点击
软件测试·移动开发·harmonyos·arkts·回归测试