• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# 数据请求
2
3> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:**
4> - 从API Version 6开始,该接口不再维护,推荐使用新接口[`@ohos.net.http`](js-apis-http.md)。
5>
6> - 本模块首批接口从API version 3开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
7
8
9## 导入模块
10
11
12```
13import fetch from '@system.fetch';
14```
15
16
17## fetch.fetch
18
19fetch(Object): void
20
21通过网络获取数据。
22
23**需要权限:** ohos.permission.INTERNET
24
25**系统能力:** SystemCapability.Communication.NetStack
26
27**参数:**
28| 参数名 | 类型 | 必填 | 说明 |
29| -------- | -------- | -------- | -------- |
30| url | string | 是 | 资源地址。 |
31| data | string \| Object | 否 | 请求的参数,可选类型是字符串或者json对象。详见表 data与Content-Type关系。 |
32| header | Object | 否 | 设置请求的header。 |
33| method | string | 否 | 请求方法默认为GET,可选值为:OPTIONS、GET、HEAD、POST、PUT、DELETE、TRACE。 |
34| responseType | string | 否 | 默认会根据服务器返回header中的Content-Type确定返回类型,支持文本和json格式。详见success返回值。 |
35| success | Function | 否 | 接口调用成功的回调函数。 |
36| fail | Function | 否 | 接口调用失败的回调函数。 |
37| complete | Function | 否 | 接口调用结束的回调函数。 |
38
39**表1** data与Content-Type关系
40
41| data | Content-Type | 说明 |
42| -------- | -------- | -------- |
43| string | 不设置 | Content-Type默认为 text/plain,data值作为请求的body。 |
44| string | 任意 Type | data值作为请求的body。 |
45| Object | 不设置 | Content-Type默认为application/x-www-form-urlencoded,data按照资源地址规则进行encode拼接作为请求的body。 |
46| Object | application/x-www-form-urlencoded | data按照资源地址规则进行encode拼接作为请求的body。 |
47
48success返回值:
49
50| 参数名 | 类型 | 说明 |
51| -------- | -------- | -------- |
52| code | number | 表示服务器的状态code。 |
53| data | string \| Object | 返回数据类型由responseType确定,详见表 responseType与success中data关系。 |
54| headers | Object | 表示服务器response的所有header。 |
55
56**表2** responseType与success中data关系
57
58| responseType | data | 说明 |
59| -------- | -------- | -------- |
60| 无 | string | 服务器返回的header中的type如果是text/\*或application/jsonapplication/javascriptapplication/xml,值为文本内容。 |
61| text | string | 返回文本内容。 |
62| json | Object | 返回json格式的对象。 |
63
64**示例:**
65
66```
67export default {
68  data: {
69    responseData: 'NA',
70    url: "test_url",
71  },
72  fetch: function () {
73    var that = this;
74    fetch.fetch({
75      url: that.url,
76      success: function(response) {
77        console.info("fetch success");
78        that.responseData = JSON.stringify(response);
79      },
80      fail: function() {
81        console.info("fetch fail");
82      }
83    });
84  }
85}
86```
87
88
89> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:**
90>   默认支持https,如果要支持http,需要在config.json里增加network标签,属性标识 "cleartextTraffic":  true。即:
91>
92> ```
93> {
94>   "deviceConfig": {
95>     "default": {
96>       "network": {
97>         "cleartextTraffic": true
98>       }
99>       ...
100>     }
101>   }
102>   ...
103> }
104> ```