js-apis-http.md 19.2 KB
Newer Older
C
clevercong 已提交
1
# 数据请求
C
clevercong 已提交
2 3 4 5 6 7

>![](public_sys-resources/icon-note.gif) **说明:** 
>
>本模块首批接口从API version 6开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
>

C
clevercong 已提交
8
## 导入模块
C
clevercong 已提交
9 10 11 12 13

```
import http from '@ohos.net.http';
```

C
clevercong 已提交
14
## 完整示例
C
clevercong 已提交
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58

```
import http from '@ohos.net.http';

// 每一个httpRequest对应一个http请求任务,不可复用
let httpRequest = http.createHttp();
// 用于订阅http响应头,此接口会比request请求先返回。可以根据业务需要订阅此消息
// 从API 8开始,使用on('headersReceive', Callback)替代on('headerReceive', AsyncCallback)。 8+
httpRequest.on('headersReceive', (data) => {
    console.info('header: ' + data.header);
});
httpRequest.request(
    // 填写http请求的url地址,可以带参数也可以不带参数。URL地址需要开发者自定义。GET请求的参数可以在extraData中指定
    "EXAMPLE_URL",
    {
        method: 'POST', // 可选,默认为“GET”
        // 开发者根据自身业务需要添加header字段
        header: {
            'Content-Type': 'application/json'
        },
        // 当使用POST请求时此字段用于传递内容
 
        extraData: {
            "data": "data to send",
        },
        connectTimeout: 60000, // 可选,默认为60s
        readTimeout: 60000, // 可选,默认为60s
    },(err, data) => {
        if (!err) {
            // data.result为http响应内容,可根据业务需要进行解析
            console.info('Result:' + data.result);
            console.info('code:' + data.responseCode);
            // data.header为http响应头,可根据业务需要进行解析
            console.info('header:' + data.header);
            console.info('cookies:' + data.cookies); // 8+
        } else {
            console.info('error:' + err);
            // 当该请求使用完毕时,调用destroy方法主动销毁。
            httpRequest.destroy();
        }
    }
);
```

C
clevercong 已提交
59
## http.createHttp
C
clevercong 已提交
60 61 62 63 64

createHttp\(\): HttpRequest

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

C
clevercong 已提交
65
**系统能力**:SystemCapability.Communication.NetStack
C
clevercong 已提交
66

C
clevercong 已提交
67
**返回值:**
C
clevercong 已提交
68

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

C
clevercong 已提交
73 74 75 76 77 78
**示例:**

```
import http from '@ohos.net.http';
let httpRequest = http.createHttp();
```
C
clevercong 已提交
79 80


C
clevercong 已提交
81
## HttpRequest
C
clevercong 已提交
82

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

C
clevercong 已提交
85
### request
C
clevercong 已提交
86 87 88 89 90

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

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

C
clevercong 已提交
91 92
**需要权限**:ohos.permission.INTERNET

C
clevercong 已提交
93
**系统能力**:SystemCapability.Communication.NetStack
C
clevercong 已提交
94

C
clevercong 已提交
95
**参数:**
C
clevercong 已提交
96

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

C
clevercong 已提交
102
**示例:**
C
clevercong 已提交
103

C
clevercong 已提交
104 105 106 107 108 109 110 111 112 113 114 115
```
httpRequest.request("EXAMPLE_URL", (err, data) => {
  if (!err) {
    console.info('Result:' + data.result);
    console.info('code:' + data.responseCode);
    console.info('header:' + data.header);
    console.info('cookies:' + data.cookies); // 8+
  } else {
    console.info('error:' + err.data);
  }
});
```
C
clevercong 已提交
116

C
clevercong 已提交
117
### request
C
clevercong 已提交
118 119 120 121 122

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

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

C
clevercong 已提交
123 124
**需要权限**:ohos.permission.INTERNET

C
clevercong 已提交
125
**系统能力**:SystemCapability.Communication.NetStack
C
clevercong 已提交
126

C
clevercong 已提交
127
**参数:**
C
clevercong 已提交
128

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

C
clevercong 已提交
135
**示例:**
C
clevercong 已提交
136

C
clevercong 已提交
137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160
```
httpRequest.request("EXAMPLE_URL",
{
  method: 'GET',
  header: {
	'Content-Type': 'application/json'
  },
  readTimeout: 60000,
  connectTimeout: 60000
},(err, data) => {
  if (!err) {
	console.info('Result:' + data.result);
	console.info('code:' + data.responseCode);
	console.info('header:' + 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']);
	console.info('header.Date:' + data.header.Date);
	console.info('header.Server:' + data.header.Server);
  } else {
	console.info('error:' + err.data);
  }
});
```
C
clevercong 已提交
161 162


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

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

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

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

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

C
clevercong 已提交
173 174 175 176 177
**参数:**

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

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

| 类型                  | 说明                              |
| :-------------------- | :-------------------------------- |
C
clevercong 已提交
184
| Promise<[HttpResponse](#httpresponse)> | 以Promise形式返回发起请求的结果。 |
C
clevercong 已提交
185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210


**示例:**

```
let promise = httpRequest.request("EXAMPLE_URL", {
  method: "GET",
  connectTimeout: 60000,
  readTimeout: 60000,
  header: {
	'Content-Type': 'application/json'
  }
});
promise.then((value) => {
	console.info('Result:' + value.result);
	console.info('code:' + value.responseCode);
	console.info('header:' + value.header);
	console.info('cookies:' + value.cookies); // 8+
	console.info('header['Content-Type']:' + value.header['Content-Type']);
	console.info('header['Status-Line']:' + value.header['Status-Line']);
	console.info('header.Date:' + value.header.Date);
	console.info('header.Server:' + value.header.Server);
}).catch((err) => {
	console.error(`errCode:${err.code}, errMessage:${err.data}`);
});
```
C
clevercong 已提交
211

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

destroy\(\): void

中断请求任务。

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

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

C
clevercong 已提交
222 223 224
```
httpRequest.destroy();
```
C
clevercong 已提交
225

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

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

订阅HTTP Response Header 事件。

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

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

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

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

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

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


C
clevercong 已提交
257
### off\('headerReceive'\)
C
clevercong 已提交
258

C
clevercong 已提交
259
off\(type: 'headerReceive', callback?: AsyncCallback<Object\>\): void
C
clevercong 已提交
260 261 262 263 264

取消订阅HTTP Response Header 事件。

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

C
clevercong 已提交
269
**系统能力**:SystemCapability.Communication.NetStack
C
clevercong 已提交
270

C
clevercong 已提交
271
**参数:**
C
clevercong 已提交
272

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

C
clevercong 已提交
278
**示例:**
C
clevercong 已提交
279

C
clevercong 已提交
280 281 282 283 284 285 286 287 288 289
```
httpRequest.on('headerReceive', (err, data) => {
  if (!err) {
	console.info('header: ' + data.header);
  } else {
	console.info('error:' + err.data);
  }
});
httpRequest.off('headerReceive');
```
C
clevercong 已提交
290

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

C
clevercong 已提交
293
on\(type: 'headersReceive', callback: Callback<Object\>\): void
C
clevercong 已提交
294 295 296

订阅HTTP Response Header 事件。

C
clevercong 已提交
297
**系统能力**:SystemCapability.Communication.NetStack
C
clevercong 已提交
298

C
clevercong 已提交
299
**参数:**
C
clevercong 已提交
300

C
clevercong 已提交
301 302 303 304
| 参数名   | 类型               | 必填 | 说明                               |
| -------- | ------------------ | ---- | ---------------------------------- |
| type     | string             | 是   | 订阅的事件类型:'headersReceive'。 |
| callback | Callback\<Object\> | 是   | 回调函数。                         |
C
clevercong 已提交
305

C
clevercong 已提交
306
**示例:**
C
clevercong 已提交
307

C
clevercong 已提交
308 309 310 311 312
```
httpRequest.on('headersReceive', (data) => {
  console.info('header: ' + data.header);
});
```
C
clevercong 已提交
313 314


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

C
clevercong 已提交
317
off\(type: 'headersReceive', callback?: Callback<Object\>\): void
C
clevercong 已提交
318 319 320 321 322 323

取消订阅HTTP Response Header 事件。

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

C
clevercong 已提交
324
**系统能力**:SystemCapability.Communication.NetStack
C
clevercong 已提交
325

C
clevercong 已提交
326
**参数:**
C
clevercong 已提交
327

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

C
clevercong 已提交
333
**示例:**
C
clevercong 已提交
334

C
clevercong 已提交
335 336 337
```
httpRequest.off('headersReceive');
```
C
clevercong 已提交
338

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

C
clevercong 已提交
341
once\(type: 'headersReceive', callback: Callback<Object\>\): void
C
clevercong 已提交
342 343 344

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

C
clevercong 已提交
345
**系统能力**:SystemCapability.Communication.NetStack
C
clevercong 已提交
346

C
clevercong 已提交
347
**参数:**
C
clevercong 已提交
348

C
clevercong 已提交
349 350 351 352
| 参数名   | 类型               | 必填 | 说明                               |
| -------- | ------------------ | ---- | ---------------------------------- |
| type     | string             | 是   | 订阅的事件类型:'headersReceive'。 |
| callback | Callback\<Object\> | 是   | 回调函数。                         |
C
clevercong 已提交
353

C
clevercong 已提交
354
**示例:**
C
clevercong 已提交
355

C
clevercong 已提交
356 357 358 359 360
```
httpRequest.once('headersReceive', (data) => {
  console.info('header: ' + data.header);
});
```
C
clevercong 已提交
361

C
clevercong 已提交
362
## HttpRequestOptions
C
clevercong 已提交
363 364 365

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

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

| 参数名          | 类型                                 | 必填 | 说明                                                       |
C
clevercong 已提交
369
| -------------- | ------------------------------------ | ---- | ---------------------------------------------------------- |
C
clevercong 已提交
370 371
| method         | [RequestMethod](#requestmethod) | 否   | 请求方式。                                                 |
| extraData      | string \| Object  \| ArrayBuffer<sup>8+</sup> | 否   | 发送请求的额外数据。<br />- 当HTTP请求为POST、PUT等方法时,此字段为HTTP请求的content。<br />- 当HTTP请求为GET、OPTIONS、DELETE、TRACE、CONNECT等方法时,此字段为HTTP请求的参数补充,参数内容会拼接到URL中进行发送。<sup>8+</sup><br />- 开发者传入string对象,开发者需要自行编码,将编码后的string传入。<sup>8+</sup> |
C
clevercong 已提交
372 373 374 375
| header         | Object                               | 否   | HTTP请求头字段。默认{'Content-Type': 'application/json'}。 |
| readTimeout    | number                               | 否   | 读取超时时间。单位为毫秒(ms),默认为60000ms。            |
| connectTimeout | number                               | 否   | 连接超时时间。单位为毫秒(ms),默认为60000ms。            |

C
clevercong 已提交
376
## RequestMethod
C
clevercong 已提交
377 378 379

HTTP 请求方法。

C
clevercong 已提交
380 381 382 383 384 385 386 387 388 389 390 391
**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetStack。

| 名称    | 值      | 说明                |
| :------ | ------- | :------------------ |
| 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 已提交
392

C
clevercong 已提交
393
## ResponseCode
C
clevercong 已提交
394 395 396

发起请求返回的响应码。

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

| 名称              | 值   | 说明                                                         |
C
clevercong 已提交
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 431 432 433 434 435 436
| ----------------- | ---- | ------------------------------------------------------------ |
| 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 已提交
437
## HttpResponse
C
clevercong 已提交
438 439 440

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

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

C
clevercong 已提交
443 444 445 446 447 448
| 参数名               | 类型                                         | 必填 | 说明                                                         |
| -------------------- | -------------------------------------------- | ---- | ------------------------------------------------------------ |
| result               | string \| Object \| ArrayBuffer<sup>8+</sup> | 是   | Http请求根据响应头中Content-type类型返回对应的响应格式内容:<br />- application/json:返回JSON格式的字符串,如需Http响应具体内容,需开发者自行解析<br />- application/octet-stream:ArrayBuffer<br />- 其他:string |
| responseCode         | [ResponseCode](#responsecode) \| number      | 是   | 回调函数执行成功时,此字段为[ResponseCode](#responsecode)。若执行失败,错误码将会从AsyncCallback中的err字段返回。错误码如下:<br />- 200:通用错误<br />- 202:参数错误<br />- 300:I/O错误 |
| 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']; |
| cookies<sup>8+</sup> | Array\<string\>                              | 是   | 服务器返回的 cookies。                                       |
C
clevercong 已提交
449