harmonyOS 网络请求

第一步:在module.json中添加权限

"requestPermissions": [
      {
        "name": "ohos.permission.INTERNET",
      }
    ]

第二步:实现网络请求工具类

import http from '@ohos.net.http'
class HttpModel {
  baseUrl: string = 'https://blog.csdn.net/weixin_71403100/article/details/136195958'

  reqHttp():Promise<string> {
    return new Promise((resolve, reject) => {
      //1.创建http请求
      let httpRequest = http.createHttp()
      //2.发送请求
      httpRequest.request(
        `${this.baseUrl}`,
        {
          method: http.RequestMethod.POST,
          // extraData: { 'username': 'admin', 'password': 'admin' },
          header: {
            'X-Tenant-ID': '1',
            'Content-Type': 'application/json'
          },
          connectTimeout: 10000,
          readTimeout: 10000
        },
      ).then(resp => {
        if (resp.responseCode === 200) {
          //查询成功
          console.log('http--成功', resp.result)
          resolve(JSON.parse(resp.result.toString()))
          return resp.result
        } else {
          console.log('http--失败', resp.result)
          reject('查询失败')
          return resp.result
        }
      })
        .catch(error => {
          console.info('error:' + JSON.stringify(error))
          reject('查询失败')
          return '查询失败'
        })
    })
  }
}

const httpModel = new HttpModel()

export default httpModel as HttpModel

第三步:实现网络请求调用

import HttpModel from '../moudle/HttpModel'
import webview from '@ohos.web.webview';

@Entry
@Component
struct Index {
  controller: webview.WebviewController = new webview.WebviewController();

  aboutToAppear(): void {
    // 配置Web开启调试模式
    webview.WebviewController.setWebDebuggingAccess(true);
  }

  build() {
    Column() {
      Button('网络请求').onClick(() => {
        HttpModel.reqHttp()
      }).width('80%')
        .margin(10)
      Web({ src: 'https://blog.csdn.net/weixin_71403100/article/details/136195958', controller: this.controller })
        .height(100)

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

补充特殊情况使用:

 //请求头格式
header: {
            'Content-Type': 'application/x-www-form-urlencoded',
          }
//转成url编码
let toServerJson = {
      "cipher": "775E7375E9415817A6F6E79C517198C8A2F0B799EEC823",
      "keyI": "0",
      "remark": "",
      "sign": "979BD364B643D1569748ECD1E2A74B8BE"
    }
    // 将 JSON 对象转换为字符串
    const jsonString = JSON.stringify(toServerJson);
    // 对字符串进行 URL 编码
    const urlEncodedString = encodeURIComponent(jsonString);
//参数拼接
extraData: "data=" + urlEncodedString,

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值