鸿蒙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中封装了很多获取网络数据的组件,后面再一一学习。

相关推荐
贾伟康28 分钟前
HarmonyOS API 26 Navigation 自适应模式:mode、分栏切换与窗口断点治理
harmonyos·arkts·arkui·navigation·自适应布局
贾伟康39 分钟前
【转盘决定吧|07】HarmonyOS ArkTS 6.0.2.130 趣味题库:场景分类、随机选择与详情页解耦
harmonyos·arkts·路由·数据建模·arkui
贾伟康1 小时前
【电路实验模拟|03】HarmonyOS ArkTS 交通灯实战:用定时状态切换红黄绿灯
harmonyos·arkts·canvas·arkui·交通灯
贾伟康18 小时前
HarmonyOS API 26 嵌套 Navigation:getParent、父子栈边界与返回分发
harmonyos·arkts·navigation·嵌套路由·navpathstack
行者-全栈开发19 小时前
【鸿蒙心迹】多线程并发实战——TaskPool 与 Worker 选型与踩坑(HarmonyOS 7.x)
华为·harmonyos·多线程并发·worker·taskpool·线程通信·harmonyos 并发
OH_TPC21 小时前
@ohos/aki 源码解读(一):一行绑定背后,宏、模板与索引分发
harmonyos
贾伟康1 天前
【解压时刻|13】HarmonyOS ArkTS 启动链路审计:从 EntryAbility、AppStore 到 Navigation 首屏
harmonyos·arkts·appstorage·应用启动·entryability
贾伟康1 天前
【古诗词闯关|12】HarmonyOS ArkTS 单页组件拆分实战:降低题库、闯关与结果弹层耦合
harmonyos·arkts·状态管理·arkui·组件化
威哥爱编程1 天前
模拟面试智能体开发实战 07:答完一题就点评一题,结构化输出给分建议,让每道题都变成复盘
python·agent·harmonyos
威哥爱编程1 天前
模拟面试智能体开发实战 08:总评报告先过三道闸,防泄题防夸大防错建议,才敢发到候选人手上
python·agent·harmonyos