Arkts完成数据请求http以及使用axios第三方库

javascript 复制代码
import http from '@ohos.net.http'
@Entry
@Component
struct HttpPage {
  @State message: string = 'Hello World'

  build() {
    Column({space:20}) {
      Row(){
        Button('发送http请求')
          .onClick(()=>{
            let httpRequest = http.createHttp();
            httpRequest.request(
              'https://zzgoodqc.cn/index.php/index/qus/getquestionlist',
              {
                method:http.RequestMethod.POST,
                extraData:{
                  sn:'1001'
                }
              }
            )
              .then(resp=>{
                console.log("resp=>",JSON.stringify(resp))
                if(resp.responseCode === 200){
                  console.log(resp.result.toString())
                }
              }).catch(err=>{
              console.log('请求错误err=>',err)
            })

          })
      }

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

以上是方案1:默认数据请求

方案二:使用axios第三方库请求接口

第一步:安装aixos,执行

javascript 复制代码
ohpm install @ohos/axios

第二步:注意配置网络权限,在module.json5文件中

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

第三步:类似vue,正常引入使用

javascript 复制代码
import axios from  '@ohos/axios'
@Entry
@Component
struct HttpPage {
  @State message: string = 'Hello World'

  build() {
    Column({space:20}) {
   Row(){
          Button('发送axios请求')
            .onClick(()=>{
              axios.post(
                'https://zzgoodqc.cn/index.php/index/qus/getquestionlist',
                {
                  sn:'1001'
                }
              ).then(response=>{
                console.log("response=>",JSON.stringify( response))
              }).catch(err=>{
                console.log('err=>',err)
              })
            })

        }


    }
    .width('100%')
    .height('100%')
  }
}
相关推荐
zym大哥大38 分钟前
HTTP协议重定向及交互
网络·网络协议·http
言之。2 小时前
Go语言Context机制深度解析:从原理到实践
服务器·网络·golang
Antonio9152 小时前
【网络编程】UDP协议 和 Socket编程
网络·udp·网络编程
weixin_467209282 小时前
zynq上的裸机lwip网络性能测试iperf使用心得
网络
照海19Gin4 小时前
HCIA-Datacom 高阶:VLAN、VLANIF 与静态路由综合实验
网络·智能路由器
Zz_waiting.4 小时前
网络原理 - 11(HTTP/HTTPS - 2 - 请求)
运维·网络·网络协议·mysql·http·https·抓包
lifewange4 小时前
jmeter-Beashell获取请求body data
网络协议·jmeter·http
JhonKI5 小时前
【Linux网络】深入解析I/O多路转接 - Select
linux·运维·网络
精神病不行计算机不上班5 小时前
【计网】计算机网络的类别与性能
网络·计算机网络