鸿蒙网络请求

203 阅读1分钟
import http from '@ohos.net.http';
@Entry
@Component
struct MyText {
  // 声明写在build之前
  @State message: string = '还没有数据'
  aboutToAppear(){
    let httpRequest = http.createHttp();
    httpRequest.on('headersReceive', (header) => {
      console.info('header: ' + JSON.stringify(header));
    });
    httpRequest.request(
      // 填写HTTP请求的URL地址,可以带参数也可以不带参数。URL地址需要开发者自定义。请求的参数可以在extraData中指定
      //"https:需要请求的url",
      "https://jsonplaceholder.typicode.com/posts",
      {
        method: http.RequestMethod.GET, // 可选,默认为http.RequestMethod.GET
        // 开发者根据自身业务需要添加header字段
        header: {
          'Content-Type': 'application/json'
        },
      }, (err, data) => {
      if (!err) {
        this.message = JSON.stringify(data.result)
      } else {
        console.info('error:' + JSON.stringify(err));
        // 取消订阅HTTP响应头事件
        httpRequest.off('headersReceive');
        // 当该请求使用完毕时,调用destroy方法主动销毁。
        httpRequest.destroy();
      }
    }
    );
  }
  build() {
    Row({ space: 200 }) {
      Text(this.message)
        .height('300')
        .fontSize(14)
        .position({x:20,y:100})
        .align(Alignment.Center)
    }
  }
}