js-apis-http.md 25.9 KB
Newer Older
C
clevercong 已提交
1
# 数据请求
C
clevercong 已提交
2

3
本模块提供HTTP数据请求能力。应用可以通过HTTP发起一个数据请求,支持常见的GET、POST、OPTIONS、HEAD、PUT、DELETE、TRACE、CONNECT方法。
4

L
liyufan 已提交
5
>**说明:**
C
clevercong 已提交
6 7 8 9
>
>本模块首批接口从API version 6开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
>

C
clevercong 已提交
10
## 导入模块
C
clevercong 已提交
11

Z
zengyawen 已提交
12
```js
C
clevercong 已提交
13 14 15
import http from '@ohos.net.http';
```

C
clevercong 已提交
16
## 完整示例
C
clevercong 已提交
17

Z
zengyawen 已提交
18
```js
C
clevercong 已提交
19 20
import http from '@ohos.net.http';

21
// 每一个httpRequest对应一个HTTP请求任务,不可复用
C
clevercong 已提交
22
let httpRequest = http.createHttp();
23
// 用于订阅HTTP响应头,此接口会比request请求先返回。可以根据业务需要订阅此消息
C
clevercong 已提交
24
// 从API 8开始,使用on('headersReceive', Callback)替代on('headerReceive', AsyncCallback)。 8+
C
clevercong 已提交
25 26
httpRequest.on('headersReceive', (header) => {
    console.info('header: ' + JSON.stringify(header));
C
clevercong 已提交
27 28
});
httpRequest.request(
29
    // 填写HTTP请求的URL地址,可以带参数也可以不带参数。URL地址需要开发者自定义。请求的参数可以在extraData中指定
C
clevercong 已提交
30 31
    "EXAMPLE_URL",
    {
C
clevercong 已提交
32
        method: http.RequestMethod.POST, // 可选,默认为http.RequestMethod.GET
C
clevercong 已提交
33 34 35 36 37 38 39 40
        // 开发者根据自身业务需要添加header字段
        header: {
            'Content-Type': 'application/json'
        },
        // 当使用POST请求时此字段用于传递内容
        extraData: {
            "data": "data to send",
        },
L
liyufan 已提交
41 42 43
        expectDataType: http.HttpDataType.STRING, // 可选,指定返回数据的类型
        usingCache: true, // 可选,默认为true
        priority: 1, // 可选,默认为1
44 45
        connectTimeout: 60000, // 可选,默认为60000ms
        readTimeout: 60000, // 可选,默认为60000ms
L
liyufan 已提交
46
        usingProtocol: http.HttpProtocol.HTTP1_1, // 可选,协议类型默认值由系统自动指定
C
clevercong 已提交
47
    }, (err, data) => {
C
clevercong 已提交
48
        if (!err) {
49
            // data.result为HTTP响应内容,可根据业务需要进行解析
C
clevercong 已提交
50 51
            console.info('Result:' + data.result);
            console.info('code:' + data.responseCode);
52
            // data.header为HTTP响应头,可根据业务需要进行解析
C
clevercong 已提交
53
            console.info('header:' + JSON.stringify(data.header));
C
clevercong 已提交
54 55
            console.info('cookies:' + data.cookies); // 8+
        } else {
C
clevercong 已提交
56
            console.info('error:' + JSON.stringify(err));
C
clevercong 已提交
57 58 59 60 61 62 63
            // 当该请求使用完毕时,调用destroy方法主动销毁。
            httpRequest.destroy();
        }
    }
);
```

C
clevercong 已提交
64
## http.createHttp
C
clevercong 已提交
65 66 67

createHttp\(\): HttpRequest

68
创建一个HTTP请求,里面包括发起请求、中断请求、订阅/取消订阅HTTP Response Header事件。每一个HttpRequest对象对应一个HTTP请求。如需发起多个HTTP请求,须为每个HTTP请求创建对应HttpRequest对象。
C
clevercong 已提交
69

C
clevercong 已提交
70
**系统能力**:SystemCapability.Communication.NetStack
C
clevercong 已提交
71

C
clevercong 已提交
72
**返回值:**
C
clevercong 已提交
73

C
clevercong 已提交
74 75 76
| 类型        | 说明                                                         |
| :---------- | :----------------------------------------------------------- |
| HttpRequest | 返回一个HttpRequest对象,里面包括request、destroy、on和off方法。 |
C
clevercong 已提交
77

C
clevercong 已提交
78 79
**示例:**

Z
zengyawen 已提交
80
```js
C
clevercong 已提交
81 82 83
import http from '@ohos.net.http';
let httpRequest = http.createHttp();
```
C
clevercong 已提交
84

C
clevercong 已提交
85
## HttpRequest
C
clevercong 已提交
86

87
HTTP请求任务。在调用HttpRequest的方法前,需要先通过[createHttp\(\)](#httpcreatehttp)创建一个任务。
C
clevercong 已提交
88

C
clevercong 已提交
89
### request
C
clevercong 已提交
90 91 92 93 94

request\(url: string, callback: AsyncCallback\<HttpResponse\>\):void

根据URL地址,发起HTTP网络请求,使用callback方式作为异步方法。

C
clevercong 已提交
95 96
**需要权限**:ohos.permission.INTERNET

C
clevercong 已提交
97
**系统能力**:SystemCapability.Communication.NetStack
C
clevercong 已提交
98

C
clevercong 已提交
99
**参数:**
C
clevercong 已提交
100

101 102 103
| 参数名   | 类型                                           | 必填 | 说明                    |
| -------- | ---------------------------------------------- | ---- | ----------------------- |
| url      | string                                         | 是   | 发起网络请求的URL地址。 |
C
clevercong 已提交
104
| callback | AsyncCallback\<[HttpResponse](#httpresponse)\> | 是   | 回调函数。              |
C
clevercong 已提交
105

C
clevercong 已提交
106
**示例:**
C
clevercong 已提交
107

Z
zengyawen 已提交
108
```js
C
clevercong 已提交
109
httpRequest.request("EXAMPLE_URL", (err, data) => {
C
clevercong 已提交
110 111 112 113 114 115 116 117
    if (!err) {
        console.info('Result:' + data.result);
        console.info('code:' + data.responseCode);
        console.info('header:' + JSON.stringify(data.header));
        console.info('cookies:' + data.cookies); // 8+
    } else {
        console.info('error:' + JSON.stringify(err));
    }
C
clevercong 已提交
118 119
});
```
C
clevercong 已提交
120

C
clevercong 已提交
121
### request
C
clevercong 已提交
122 123 124 125 126

request\(url: string, options: HttpRequestOptions, callback: AsyncCallback<HttpResponse\>\):void

根据URL地址和相关配置项,发起HTTP网络请求,使用callback方式作为异步方法。

C
clevercong 已提交
127 128
**需要权限**:ohos.permission.INTERNET

C
clevercong 已提交
129
**系统能力**:SystemCapability.Communication.NetStack
C
clevercong 已提交
130

C
clevercong 已提交
131
**参数:**
C
clevercong 已提交
132

C
clevercong 已提交
133 134 135 136 137
| 参数名   | 类型                                           | 必填 | 说明                                            |
| -------- | ---------------------------------------------- | ---- | ----------------------------------------------- |
| url      | string                                         | 是   | 发起网络请求的URL地址。                         |
| options  | HttpRequestOptions                             | 是   | 参考[HttpRequestOptions](#httprequestoptions)。 |
| callback | AsyncCallback\<[HttpResponse](#httpresponse)\> | 是   | 回调函数。                                      |
C
clevercong 已提交
138

C
clevercong 已提交
139
**示例:**
C
clevercong 已提交
140

Z
zengyawen 已提交
141
```js
C
clevercong 已提交
142 143
httpRequest.request("EXAMPLE_URL",
{
C
clevercong 已提交
144
    method: http.RequestMethod.GET,
C
clevercong 已提交
145 146 147 148 149 150 151 152 153
    header: {
        'Content-Type': 'application/json'
    },
    readTimeout: 60000,
    connectTimeout: 60000
}, (err, data) => {
    if (!err) {
        console.info('Result:' + data.result);
        console.info('code:' + data.responseCode);
C
clevercong 已提交
154
        console.info('header:' + JSON.stringify(data.header));
C
clevercong 已提交
155 156 157 158
        console.info('cookies:' + data.cookies); // 8+
        console.info('header.Content-Type:' + data.header['Content-Type']);
        console.info('header.Status-Line:' + data.header['Status-Line']);
    } else {
C
clevercong 已提交
159
        console.info('error:' + JSON.stringify(err));
C
clevercong 已提交
160
    }
C
clevercong 已提交
161 162
});
```
C
clevercong 已提交
163

C
clevercong 已提交
164
### request
C
clevercong 已提交
165 166 167 168 169

request\(url: string, options? : HttpRequestOptions\): Promise<HttpResponse\>

根据URL地址,发起HTTP网络请求,使用Promise方式作为异步方法。

C
clevercong 已提交
170 171
**需要权限**:ohos.permission.INTERNET

C
clevercong 已提交
172
**系统能力**:SystemCapability.Communication.NetStack
C
clevercong 已提交
173

C
clevercong 已提交
174 175
**参数:**

176 177 178
| 参数名  | 类型               | 必填 | 说明                                            |
| ------- | ------------------ | ---- | ----------------------------------------------- |
| url     | string             | 是   | 发起网络请求的URL地址。                         |
L
liyufan 已提交
179
| options | HttpRequestOptions | 否   | 参考[HttpRequestOptions](#httprequestoptions)。 |
C
clevercong 已提交
180

C
clevercong 已提交
181 182
**返回值:**

183 184
| 类型                                   | 说明                              |
| :------------------------------------- | :-------------------------------- |
C
clevercong 已提交
185
| Promise<[HttpResponse](#httpresponse)> | 以Promise形式返回发起请求的结果。 |
C
clevercong 已提交
186 187 188 189


**示例:**

Z
zengyawen 已提交
190
```js
C
clevercong 已提交
191
let promise = httpRequest.request("EXAMPLE_URL", {
C
clevercong 已提交
192
    method: http.RequestMethod.GET,
C
clevercong 已提交
193 194 195 196 197
    connectTimeout: 60000,
    readTimeout: 60000,
    header: {
        'Content-Type': 'application/json'
    }
C
clevercong 已提交
198
});
C
clevercong 已提交
199 200 201 202 203 204 205
promise.then((data) => {
    console.info('Result:' + data.result);
    console.info('code:' + data.responseCode);
    console.info('header:' + JSON.stringify(data.header));
    console.info('cookies:' + data.cookies); // 8+
    console.info('header.Content-Type:' + data.header['Content-Type']);
    console.info('header.Status-Line:' + data.header['Status-Line']);
C
clevercong 已提交
206
}).catch((err) => {
C
clevercong 已提交
207
    console.info('error:' + JSON.stringify(err));
C
clevercong 已提交
208 209
});
```
C
clevercong 已提交
210

C
clevercong 已提交
211
### destroy
C
clevercong 已提交
212 213 214 215 216

destroy\(\): void

中断请求任务。

C
clevercong 已提交
217
**系统能力**:SystemCapability.Communication.NetStack
C
clevercong 已提交
218

C
clevercong 已提交
219
**示例:**
C
clevercong 已提交
220

Z
zengyawen 已提交
221
```js
C
clevercong 已提交
222 223
httpRequest.destroy();
```
C
clevercong 已提交
224

C
clevercong 已提交
225
### on\('headerReceive'\)
C
clevercong 已提交
226

C
clevercong 已提交
227
on\(type: 'headerReceive', callback: AsyncCallback<Object\>\): void
C
clevercong 已提交
228 229 230

订阅HTTP Response Header 事件。

L
liyufan 已提交
231
>![](public_sys-resources/icon-note.gif) **说明:**
232
>此接口已废弃,建议使用[on\('headersReceive'\)<sup>8+</sup>](#onheadersreceive8)替代。
C
clevercong 已提交
233

C
clevercong 已提交
234
**系统能力**:SystemCapability.Communication.NetStack
C
clevercong 已提交
235

C
clevercong 已提交
236
**参数:**
C
clevercong 已提交
237

C
clevercong 已提交
238 239 240 241
| 参数名   | 类型                    | 必填 | 说明                              |
| -------- | ----------------------- | ---- | --------------------------------- |
| type     | string                  | 是   | 订阅的事件类型,'headerReceive'。 |
| callback | AsyncCallback\<Object\> | 是   | 回调函数。                        |
C
clevercong 已提交
242

C
clevercong 已提交
243
**示例:**
C
clevercong 已提交
244

Z
zengyawen 已提交
245
```js
C
clevercong 已提交
246
httpRequest.on('headerReceive', (err, data) => {
C
clevercong 已提交
247 248 249 250 251
    if (!err) {
        console.info('header: ' + JSON.stringify(data));
    } else {
        console.info('error:' + JSON.stringify(err));
    }
C
clevercong 已提交
252 253
});
```
C
clevercong 已提交
254

C
clevercong 已提交
255
### off\('headerReceive'\)
C
clevercong 已提交
256

C
clevercong 已提交
257
off\(type: 'headerReceive', callback?: AsyncCallback<Object\>\): void
C
clevercong 已提交
258 259 260

取消订阅HTTP Response Header 事件。

L
liyufan 已提交
261
>![](public_sys-resources/icon-note.gif) **说明:**
C
clevercong 已提交
262
>
C
clevercong 已提交
263
>1. 此接口已废弃,建议使用[off\('headersReceive'\)<sup>8+</sup>](#offheadersreceive8)替代。
C
clevercong 已提交
264 265 266
>
>2. 可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。

C
clevercong 已提交
267
**系统能力**:SystemCapability.Communication.NetStack
C
clevercong 已提交
268

C
clevercong 已提交
269
**参数:**
C
clevercong 已提交
270

C
clevercong 已提交
271 272 273 274
| 参数名   | 类型                    | 必填 | 说明                                  |
| -------- | ----------------------- | ---- | ------------------------------------- |
| type     | string                  | 是   | 取消订阅的事件类型,'headerReceive'。 |
| callback | AsyncCallback\<Object\> | 否   | 回调函数。                            |
C
clevercong 已提交
275

C
clevercong 已提交
276
**示例:**
C
clevercong 已提交
277

Z
zengyawen 已提交
278
```js
C
clevercong 已提交
279 280
httpRequest.off('headerReceive');
```
C
clevercong 已提交
281

C
clevercong 已提交
282
### on\('headersReceive'\)<sup>8+</sup>
C
clevercong 已提交
283

C
clevercong 已提交
284
on\(type: 'headersReceive', callback: Callback<Object\>\): void
C
clevercong 已提交
285 286 287

订阅HTTP Response Header 事件。

C
clevercong 已提交
288
**系统能力**:SystemCapability.Communication.NetStack
C
clevercong 已提交
289

C
clevercong 已提交
290
**参数:**
C
clevercong 已提交
291

C
clevercong 已提交
292 293 294 295
| 参数名   | 类型               | 必填 | 说明                               |
| -------- | ------------------ | ---- | ---------------------------------- |
| type     | string             | 是   | 订阅的事件类型:'headersReceive'。 |
| callback | Callback\<Object\> | 是   | 回调函数。                         |
C
clevercong 已提交
296

C
clevercong 已提交
297
**示例:**
C
clevercong 已提交
298

Z
zengyawen 已提交
299
```js
C
clevercong 已提交
300 301
httpRequest.on('headersReceive', (header) => {
    console.info('header: ' + JSON.stringify(header));
C
clevercong 已提交
302 303
});
```
C
clevercong 已提交
304

C
clevercong 已提交
305
### off\('headersReceive'\)<sup>8+</sup>
C
clevercong 已提交
306

C
clevercong 已提交
307
off\(type: 'headersReceive', callback?: Callback<Object\>\): void
C
clevercong 已提交
308 309 310

取消订阅HTTP Response Header 事件。

L
liyufan 已提交
311
>![](public_sys-resources/icon-note.gif) **说明:**
C
clevercong 已提交
312 313
>可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。

C
clevercong 已提交
314
**系统能力**:SystemCapability.Communication.NetStack
C
clevercong 已提交
315

C
clevercong 已提交
316
**参数:**
C
clevercong 已提交
317

C
clevercong 已提交
318 319 320 321
| 参数名   | 类型               | 必填 | 说明                                   |
| -------- | ------------------ | ---- | -------------------------------------- |
| type     | string             | 是   | 取消订阅的事件类型:'headersReceive'。 |
| callback | Callback\<Object\> | 否   | 回调函数。                             |
C
clevercong 已提交
322

C
clevercong 已提交
323
**示例:**
C
clevercong 已提交
324

Z
zengyawen 已提交
325
```js
C
clevercong 已提交
326 327
httpRequest.off('headersReceive');
```
C
clevercong 已提交
328

C
clevercong 已提交
329
### once\('headersReceive'\)<sup>8+</sup>
C
clevercong 已提交
330

C
clevercong 已提交
331
once\(type: 'headersReceive', callback: Callback<Object\>\): void
C
clevercong 已提交
332 333 334

订阅HTTP Response Header 事件,但是只触发一次。一旦触发之后,订阅器就会被移除。使用callback方式作为异步方法。

C
clevercong 已提交
335
**系统能力**:SystemCapability.Communication.NetStack
C
clevercong 已提交
336

C
clevercong 已提交
337
**参数:**
C
clevercong 已提交
338

C
clevercong 已提交
339 340 341 342
| 参数名   | 类型               | 必填 | 说明                               |
| -------- | ------------------ | ---- | ---------------------------------- |
| type     | string             | 是   | 订阅的事件类型:'headersReceive'。 |
| callback | Callback\<Object\> | 是   | 回调函数。                         |
C
clevercong 已提交
343

C
clevercong 已提交
344
**示例:**
C
clevercong 已提交
345

Z
zengyawen 已提交
346
```js
C
clevercong 已提交
347 348
httpRequest.once('headersReceive', (header) => {
    console.info('header: ' + JSON.stringify(header));
C
clevercong 已提交
349 350
});
```
C
clevercong 已提交
351

C
clevercong 已提交
352
## HttpRequestOptions
C
clevercong 已提交
353 354 355

发起请求可选参数的类型和取值范围。

C
clevercong 已提交
356 357
**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetStack。

L
liyufan 已提交
358
| 名称         | 类型                                          | 必填 | 说明                                                         |
359 360
| -------------- | --------------------------------------------- | ---- | ------------------------------------------------------------ |
| method         | [RequestMethod](#requestmethod)               | 否   | 请求方式。                                                   |
Z
zhuwenchao 已提交
361
| extraData      | string \| Object  \| ArrayBuffer<sup>6+</sup> | 否   | 发送请求的额外数据。<br />- 当HTTP请求为POST、PUT等方法时,此字段为HTTP请求的content。<br />- 当HTTP请求为GET、OPTIONS、DELETE、TRACE、CONNECT等方法时,此字段为HTTP请求的参数补充,参数内容会拼接到URL中进行发送。<sup>6+</sup><br />- 开发者传入string对象,开发者需要自行编码,将编码后的string传入。<sup>6+</sup> |
L
liyufan 已提交
362
| expectDataType<sup>9+</sup>  | [HttpDataType](#httpdatatype9)   | 否   | 指定返回数据的类型。如果设置了此参数,系统将优先返回指定的类型。 |
L
liyufan123 已提交
363
| usingCache<sup>9+</sup>      | boolean                         | 否   | 是否使用缓存,默认为true。   |
L
liyufan 已提交
364
| priority<sup>9+</sup>        | number                          | 否   | 优先级,范围\[1,1000],默认是1。                           |
365 366 367
| header         | Object                                        | 否   | HTTP请求头字段。默认{'Content-Type': 'application/json'}。   |
| readTimeout    | number                                        | 否   | 读取超时时间。单位为毫秒(ms),默认为60000ms。              |
| connectTimeout | number                                        | 否   | 连接超时时间。单位为毫秒(ms),默认为60000ms。              |
L
liyufan 已提交
368
| usingProtocol<sup>9+</sup>   | [HttpProtocol](#httpprotocol9)   | 否   | 使用协议。默认值由系统自动指定。              |
C
clevercong 已提交
369

C
clevercong 已提交
370
## RequestMethod
C
clevercong 已提交
371 372 373

HTTP 请求方法。

C
clevercong 已提交
374 375 376 377
**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetStack。

| 名称    | 值      | 说明                |
| :------ | ------- | :------------------ |
L
liyufan 已提交
378 379 380 381 382 383 384 385
| OPTIONS | "OPTIONS" | HTTP 请求 OPTIONS。 |
| GET     | "GET"     | HTTP 请求 GET。     |
| HEAD    | "HEAD"    | HTTP 请求 HEAD。    |
| POST    | "POST"    | HTTP 请求 POST。    |
| PUT     | "PUT"     | HTTP 请求 PUT。     |
| DELETE  | "DELETE"  | HTTP 请求 DELETE。  |
| TRACE   | "TRACE"   | HTTP 请求 TRACE。   |
| CONNECT | "CONNECT" | HTTP 请求 CONNECT。 |
C
clevercong 已提交
386

C
clevercong 已提交
387
## ResponseCode
C
clevercong 已提交
388 389 390

发起请求返回的响应码。

C
clevercong 已提交
391 392 393
**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetStack。

| 名称              | 值   | 说明                                                         |
C
clevercong 已提交
394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430
| ----------------- | ---- | ------------------------------------------------------------ |
| OK                | 200  | 请求成功。一般用于GET与POST请求。                            |
| CREATED           | 201  | 已创建。成功请求并创建了新的资源。                           |
| ACCEPTED          | 202  | 已接受。已经接受请求,但未处理完成。                         |
| NOT_AUTHORITATIVE | 203  | 非授权信息。请求成功。                                       |
| NO_CONTENT        | 204  | 无内容。服务器成功处理,但未返回内容。                       |
| RESET             | 205  | 重置内容。                                                   |
| PARTIAL           | 206  | 部分内容。服务器成功处理了部分GET请求。                      |
| MULT_CHOICE       | 300  | 多种选择。                                                   |
| MOVED_PERM        | 301  | 永久移动。请求的资源已被永久的移动到新URI,返回信息会包括新的URI,浏览器会自动定向到新URI。 |
| MOVED_TEMP        | 302  | 临时移动。                                                   |
| SEE_OTHER         | 303  | 查看其它地址。                                               |
| NOT_MODIFIED      | 304  | 未修改。                                                     |
| USE_PROXY         | 305  | 使用代理。                                                   |
| BAD_REQUEST       | 400  | 客户端请求的语法错误,服务器无法理解。                       |
| UNAUTHORIZED      | 401  | 请求要求用户的身份认证。                                     |
| PAYMENT_REQUIRED  | 402  | 保留,将来使用。                                             |
| FORBIDDEN         | 403  | 服务器理解请求客户端的请求,但是拒绝执行此请求。             |
| NOT_FOUND         | 404  | 服务器无法根据客户端的请求找到资源(网页)。                 |
| BAD_METHOD        | 405  | 客户端请求中的方法被禁止。                                   |
| NOT_ACCEPTABLE    | 406  | 服务器无法根据客户端请求的内容特性完成请求。                 |
| PROXY_AUTH        | 407  | 请求要求代理的身份认证。                                     |
| CLIENT_TIMEOUT    | 408  | 请求时间过长,超时。                                         |
| CONFLICT          | 409  | 服务器完成客户端的PUT请求是可能返回此代码,服务器处理请求时发生了冲突。 |
| GONE              | 410  | 客户端请求的资源已经不存在。                                 |
| LENGTH_REQUIRED   | 411  | 服务器无法处理客户端发送的不带Content-Length的请求信息。     |
| PRECON_FAILED     | 412  | 客户端请求信息的先决条件错误。                               |
| ENTITY_TOO_LARGE  | 413  | 由于请求的实体过大,服务器无法处理,因此拒绝请求。           |
| REQ_TOO_LONG      | 414  | 请求的URI过长(URI通常为网址),服务器无法处理。             |
| UNSUPPORTED_TYPE  | 415  | 服务器无法处理请求的格式。                                   |
| INTERNAL_ERROR    | 500  | 服务器内部错误,无法完成请求。                               |
| NOT_IMPLEMENTED   | 501  | 服务器不支持请求的功能,无法完成请求。                       |
| BAD_GATEWAY       | 502  | 充当网关或代理的服务器,从远端服务器接收到了一个无效的请求。 |
| UNAVAILABLE       | 503  | 由于超载或系统维护,服务器暂时的无法处理客户端的请求。       |
| GATEWAY_TIMEOUT   | 504  | 充当网关或代理的服务器,未及时从远端服务器获取请求。         |
| VERSION           | 505  | 服务器请求的HTTP协议的版本。                                 |

C
clevercong 已提交
431
## HttpResponse
C
clevercong 已提交
432 433 434

request方法回调函数的返回值类型。

C
clevercong 已提交
435 436
**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetStack。

L
liyufan 已提交
437
| 名称               | 类型                                         | 必填 | 说明                                                         |
C
clevercong 已提交
438
| -------------------- | -------------------------------------------- | ---- | ------------------------------------------------------------ |
Z
zhuwenchao 已提交
439
| result               | string \| Object \| ArrayBuffer<sup>6+</sup> | 是   | HTTP请求根据响应头中Content-type类型返回对应的响应格式内容:<br />- application/json:返回JSON格式的字符串,如需HTTP响应具体内容,需开发者自行解析<br />- application/octet-stream:ArrayBuffer<br />- 其他:string |
L
liyufan 已提交
440
| resultType<sup>9+</sup> | [HttpDataType](#httpdatatype9)             | 是   | 返回值类型。                           |
441
| responseCode         | [ResponseCode](#responsecode) \| number      | 是   | 回调函数执行成功时,此字段为[ResponseCode](#responsecode)。若执行失败,错误码将会从AsyncCallback中的err字段返回。错误码参考[Response错误码](#response常用错误码)。 |
442
| header               | Object                                       | 是   | 发起HTTP请求返回来的响应头。当前返回的是JSON格式字符串,如需具体字段内容,需开发者自行解析。常见字段及解析方式如下:<br/>- Content-Type:header['Content-Type'];<br />- Status-Line:header['Status-Line'];<br />- Date:header.Date/header['Date'];<br />- Server:header.Server/header['Server']; |
C
clevercong 已提交
443
| cookies<sup>8+</sup> | Array\<string\>                              | 是   | 服务器返回的 cookies。                                       |
C
clevercong 已提交
444

L
liyufan 已提交
445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511
## http.createHttpResponseCache<sup>9+</sup>

createHttpResponseCache(cacheSize?: number): HttpResponseCache

创建一个默认的对象来存储HTTP访问请求的响应。

**系统能力**:SystemCapability.Communication.NetStack

**参数:**

| 参数名   | 类型                                    | 必填 | 说明       |
| -------- | --------------------------------------- | ---- | ---------- |
| cacheSize | number | 否 | 缓存大小最大为10\*1024\*1024(10MB),默认最大。 |

**返回值:**

| 类型        | 说明                                                         |
| :---------- | :----------------------------------------------------------- |
| [HttpResponseCache](#httpresponsecache9) | 返回一个存储HTTP访问请求响应的对象。 |

**示例:**

```js
import http from '@ohos.net.http';
let httpResponseCache = http.createHttpResponseCache();
```

## HttpResponseCache<sup>9+</sup>

存储HTTP访问请求响应的对象。

### flush<sup>9+</sup>

flush(callback: AsyncCallback\<void>): void

将缓存中的数据写入文件系统,以便在下一个HTTP请求中访问所有缓存数据,使用callback方式作为异步方法。

**系统能力**:SystemCapability.Communication.NetStack

**参数:**

| 参数名   | 类型                                    | 必填 | 说明       |
| -------- | --------------------------------------- | ---- | ---------- |
| callback | AsyncCallback\<void> | 是   | 回调函数返回写入结果。 |

**示例:**

```js
import http from '@ohos.net.http';
let httpResponseCache = http.createHttpResponseCache();
httpResponseCache.flush(err => {
  if (err) {
    console.log('flush fail');
    return;
  }
  console.log('flush success');
});
```

### flush<sup>9+</sup>

flush(): Promise\<void>

将缓存中的数据写入文件系统,以便在下一个HTTP请求中访问所有缓存数据,使用Promise方式作为异步方法。

**系统能力**:SystemCapability.Communication.NetStack

L
liyufan 已提交
512
**返回值:**
L
liyufan 已提交
513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564

| 类型                              | 说明                                  |
| --------------------------------- | ------------------------------------- |
| Promise\<void>> | 以Promise形式返回写入结果。 |

**示例:**

```js
import http from '@ohos.net.http';
let httpResponseCache = http.createHttpResponseCache();
http.flush().then(() => {
  console.log('flush success');
}).catch(err => {
  console.log('flush fail');
});
```

### delete<sup>9+</sup>

delete(callback: AsyncCallback\<void>): void

禁用缓存并删除其中的数据,使用callback方式作为异步方法。

**系统能力**:SystemCapability.Communication.NetStack

**参数:**

| 参数名   | 类型                                    | 必填 | 说明       |
| -------- | --------------------------------------- | ---- | ---------- |
| callback | AsyncCallback\<void> | 是   | 回调函数返回删除结果。|

**示例:**

```js
import http from '@ohos.net.http';
let httpResponseCache = http.createHttpResponseCache();
httpResponseCache.delete(err => {
  if (err) {
    console.log('delete fail');
    return;
  }
  console.log('delete success');
});
```
### delete<sup>9+</sup>

delete(): Promise\<void>

禁用缓存并删除其中的数据,使用Promise方式作为异步方法。

**系统能力**:SystemCapability.Communication.NetStack

L
liyufan 已提交
565
**返回值:**
L
liyufan 已提交
566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582

| 类型                              | 说明                                  |
| --------------------------------- | ------------------------------------- |
| Promise\<void> | 以Promise形式返回删除结果。 |

**示例:**

```js
import http from '@ohos.net.http';
let httpResponseCache = http.createHttpResponseCache();
httpResponseCache.delete().then() => {
  console.log('delete success');
}).catch(err => {
  console.log('delete fail');
});
```

583
## Response常用错误码
584 585 586

| 错误码 | 说明                                                         |
| ------ | ------------------------------------------------------------ |
Z
zhewei 已提交
587 588 589 590 591 592
| -1     | 参数错误。检查参数的个数与类型是否正确。                           |
| 3      | URL格式错误。检查URL的格式与语法是否正确。                         |
| 4      | 构建时无法找到内置的请求功能、协议或选项。一个功能或选项是不启用或明确禁用时,为了得到它的功能,你需要得到一个重建的libcurl。              |
| 5      | 无法解析代理,指定的代理服务器主机无法解析。建议排查:1、url地址是否正确。2、联网是否正常,网络是否可以和外部进行通信。3、是否有网络访问权限。  |
| 6      | 无法解析主机,指定的远程主机无法解析。建议排查:1、url地址是否正确。2、联网是否正常,网络是否可以和外部进行通信。3、是否有网络访问权限。       |
| 7      | 无法连接代理或主机。建议排查:1、端口号是否有问题。 2、查看本地是否开启http的代理影响的。                                    |
593

L
liyufan 已提交
594 595 596 597
## HttpDataType<sup>9+</sup>

http的数据类型。

Y
YOUR_NAME 已提交
598 599
**系统能力**:SystemCapability.Communication.NetStack

L
liyufan 已提交
600 601 602 603 604
| 名称 | 值 | 说明     |
| ------------------ | -- | ----------- |
| STRING              | 0 | 字符串类型。 |
| OBJECT              | 1 | 对象类型。    |
| ARRAY_BUFFER        | 2 | 二进制数组类型。|
L
liyufan 已提交
605 606 607 608 609

## HttpProtocol<sup>9+</sup>

http协议版本。

Y
YOUR_NAME 已提交
610 611
**系统能力**:SystemCapability.Communication.NetStack

L
liyufan 已提交
612 613 614 615
| 名称  | 说明     |
| :-------- | :----------- |
| HTTP1_1   |  协议http1.1  |
| HTTP2     |  协议http2    |