數(shù)據(jù)請求

2024-01-23 16:40 更新

本模塊提供HTTP數(shù)據(jù)請求能力。應用可以通過HTTP發(fā)起一個數(shù)據(jù)請求,支持常見的GET、POST、OPTIONS、HEAD、PUT、DELETE、TRACE、CONNECT方法。

說明

本模塊首批接口從API version 6開始支持。后續(xù)版本的新增接口,采用上角標單獨標記接口的起始版本。

導入模塊

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

完整示例

  1. // 引入包名
  2. import http from '@ohos.net.http';
  3. // 每一個httpRequest對應一個HTTP請求任務,不可復用
  4. let httpRequest = http.createHttp();
  5. // 用于訂閱HTTP響應頭,此接口會比request請求先返回??梢愿鶕?jù)業(yè)務需要訂閱此消息
  6. // 從API 8開始,使用on('headersReceive', Callback)替代on('headerReceive', AsyncCallback)。 8+
  7. httpRequest.on('headersReceive', (header) => {
  8. console.info('header: ' + JSON.stringify(header));
  9. });
  10. httpRequest.request(
  11. // 填寫HTTP請求的URL地址,可以帶參數(shù)也可以不帶參數(shù)。URL地址需要開發(fā)者自定義。請求的參數(shù)可以在extraData中指定
  12. "EXAMPLE_URL",
  13. {
  14. method: http.RequestMethod.POST, // 可選,默認為http.RequestMethod.GET
  15. // 開發(fā)者根據(jù)自身業(yè)務需要添加header字段
  16. header: {
  17. 'Content-Type': 'application/json'
  18. },
  19. // 當使用POST請求時此字段用于傳遞內容
  20. extraData: {
  21. "data": "data to send",
  22. },
  23. expectDataType: http.HttpDataType.STRING, // 可選,指定返回數(shù)據(jù)的類型
  24. usingCache: true, // 可選,默認為true
  25. priority: 1, // 可選,默認為1
  26. connectTimeout: 60000, // 可選,默認為60000ms
  27. readTimeout: 60000, // 可選,默認為60000ms
  28. usingProtocol: http.HttpProtocol.HTTP1_1, // 可選,協(xié)議類型默認值由系統(tǒng)自動指定
  29. }, (err, data) => {
  30. if (!err) {
  31. // data.result為HTTP響應內容,可根據(jù)業(yè)務需要進行解析
  32. console.info('Result:' + JSON.stringify(data.result));
  33. console.info('code:' + JSON.stringify(data.responseCode));
  34. // data.header為HTTP響應頭,可根據(jù)業(yè)務需要進行解析
  35. console.info('header:' + JSON.stringify(data.header));
  36. console.info('cookies:' + JSON.stringify(data.cookies)); // 8+
  37. // 取消訂閱HTTP響應頭事件
  38. httpRequest.off('headersReceive');
  39. // 當該請求使用完畢時,調用destroy方法主動銷毀
  40. httpRequest.destroy();
  41. } else {
  42. console.info('error:' + JSON.stringify(err));
  43. // 取消訂閱HTTP響應頭事件
  44. httpRequest.off('headersReceive');
  45. // 當該請求使用完畢時,調用destroy方法主動銷毀。
  46. httpRequest.destroy();
  47. }
  48. }
  49. );
說明

console.info()輸出的數(shù)據(jù)中包含換行符會導致數(shù)據(jù)出現(xiàn)截斷現(xiàn)象。

http.createHttp

createHttp(): HttpRequest

創(chuàng)建一個HTTP請求,里面包括發(fā)起請求、中斷請求、訂閱/取消訂閱HTTP Response Header事件。

每一個HttpRequest對象對應一個HTTP請求。如需發(fā)起多個HTTP請求,須為每個HTTP請求創(chuàng)建對應HttpRequest對象。最多只能創(chuàng)建100個HttpRequest對象。

系統(tǒng)能力:SystemCapability.Communication.NetStack

返回值:

類型

說明

HttpRequest

返回一個HttpRequest對象,里面包括request、destroy、on和off方法。

示例:

  1. import http from '@ohos.net.http';
  2. let httpRequest = http.createHttp();

HttpRequest

HTTP請求任務。在調用HttpRequest的方法前,需要先通過createHttp()創(chuàng)建一個任務。

request

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

根據(jù)URL地址,發(fā)起HTTP網(wǎng)絡請求,使用callback方式作為異步方法。

說明

此接口僅支持數(shù)據(jù)大小為5M以內的數(shù)據(jù)接收。

需要權限:ohos.permission.INTERNET

系統(tǒng)能力:SystemCapability.Communication.NetStack

參數(shù):

參數(shù)名

類型

必填

說明

url

string

發(fā)起網(wǎng)絡請求的URL地址。

callback

AsyncCallback<HttpResponse>

回調函數(shù)。

錯誤碼:

錯誤碼ID

錯誤信息

401

Parameter error.

201

Permission denied.

2300003

URL using bad/illegal format or missing URL.

2300007

Couldn't connect to server.

2300028

Timeout was reached.

2300052

Server returned nothing (no headers, no data).

2300999

Unknown Other Error.

說明

以上錯誤碼的詳細介紹參見HTTP錯誤碼。

HTTP 錯誤碼映射關系:2300000 + curl錯誤碼。更多常用錯誤碼,可參考:curl錯誤碼

示例:

  1. httpRequest.request("EXAMPLE_URL", (err, data) => {
  2. if (!err) {
  3. console.info('Result:' + data.result);
  4. console.info('code:' + data.responseCode);
  5. console.info('header:' + JSON.stringify(data.header));
  6. console.info('cookies:' + data.cookies); // 8+
  7. } else {
  8. console.info('error:' + JSON.stringify(err));
  9. }
  10. });

request

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

根據(jù)URL地址和相關配置項,發(fā)起HTTP網(wǎng)絡請求,使用callback方式作為異步方法。

說明

此接口僅支持數(shù)據(jù)大小為5M以內的數(shù)據(jù)接收。

需要權限:ohos.permission.INTERNET

系統(tǒng)能力:SystemCapability.Communication.NetStack

參數(shù):

參數(shù)名

類型

必填

說明

url

string

發(fā)起網(wǎng)絡請求的URL地址。

options

HttpRequestOptions

參考HttpRequestOptions。

callback

AsyncCallback<HttpResponse>

回調函數(shù)。

錯誤碼:

錯誤碼ID

錯誤信息

401

Parameter error.

201

Permission denied.

2300001

Unsupported protocol.

2300003

URL using bad/illegal format or missing URL.

2300005

Couldn't resolve proxy name.

2300006

Couldn't resolve host name.

2300007

Couldn't connect to server.

2300008

Weird server reply.

2300009

Access denied to remote resource.

2300016

Error in the HTTP2 framing layer.

2300018

Transferred a partial file.

2300023

Failed writing received data to disk/application.

2300025

Upload failed.

2300026

Failed to open/read local data from file/application.

2300027

Out of memory.

2300028

Timeout was reached.

2300047

Number of redirects hit maximum amount.

2300052

Server returned nothing (no headers, no data).

2300055

Failed sending data to the peer.

2300056

Failure when receiving data from the peer.

2300058

Problem with the local SSL certificate.

2300059

Couldn't use specified SSL cipher.

2300060

SSL peer certificate or SSH remote key was not OK.

2300061

Unrecognized or bad HTTP Content or Transfer-Encoding.

2300063

Maximum file size exceeded.

2300070

Disk full or allocation exceeded.

2300073

Remote file already exists.

2300077

Problem with the SSL CA cert (path? access rights?).

2300078

Remote file not found.

2300094

An authentication function returned an error.

2300999

Unknown Other Error.

說明

以上錯誤碼的詳細介紹參見HTTP錯誤碼。

HTTP 錯誤碼映射關系:2300000 + curl錯誤碼。更多常用錯誤碼,可參考:curl錯誤碼

示例:

  1. httpRequest.request("EXAMPLE_URL",
  2. {
  3. method: http.RequestMethod.GET,
  4. header: {
  5. 'Content-Type': 'application/json'
  6. },
  7. readTimeout: 60000,
  8. connectTimeout: 60000
  9. }, (err, data) => {
  10. if (!err) {
  11. console.info('Result:' + data.result);
  12. console.info('code:' + data.responseCode);
  13. console.info('header:' + JSON.stringify(data.header));
  14. console.info('cookies:' + data.cookies); // 8+
  15. console.info('header.Content-Type:' + data.header['Content-Type']);
  16. console.info('header.Status-Line:' + data.header['Status-Line']);
  17. } else {
  18. console.info('error:' + JSON.stringify(err));
  19. }
  20. });

request

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

根據(jù)URL地址,發(fā)起HTTP網(wǎng)絡請求,使用Promise方式作為異步方法。

說明

此接口僅支持數(shù)據(jù)大小為5M以內的數(shù)據(jù)接收。

需要權限:ohos.permission.INTERNET

系統(tǒng)能力:SystemCapability.Communication.NetStack

參數(shù):

參數(shù)名

類型

必填

說明

url

string

發(fā)起網(wǎng)絡請求的URL地址。

options

HttpRequestOptions

參考HttpRequestOptions。

返回值:

類型

說明

Promise<HttpResponse>

以Promise形式返回發(fā)起請求的結果。

錯誤碼:

錯誤碼ID

錯誤信息

401

Parameter error.

201

Permission denied.

2300001

Unsupported protocol.

2300003

URL using bad/illegal format or missing URL.

2300005

Couldn't resolve proxy name.

2300006

Couldn't resolve host name.

2300007

Couldn't connect to server.

2300008

Weird server reply.

2300009

Access denied to remote resource.

2300016

Error in the HTTP2 framing layer.

2300018

Transferred a partial file.

2300023

Failed writing received data to disk/application.

2300025

Upload failed.

2300026

Failed to open/read local data from file/application.

2300027

Out of memory.

2300028

Timeout was reached.

2300047

Number of redirects hit maximum amount.

2300052

Server returned nothing (no headers, no data).

2300055

Failed sending data to the peer.

2300056

Failure when receiving data from the peer.

2300058

Problem with the local SSL certificate.

2300059

Couldn't use specified SSL cipher.

2300060

SSL peer certificate or SSH remote key was not OK.

2300061

Unrecognized or bad HTTP Content or Transfer-Encoding.

2300063

Maximum file size exceeded.

2300070

Disk full or allocation exceeded.

2300073

Remote file already exists.

2300077

Problem with the SSL CA cert (path? access rights?).

2300078

Remote file not found.

2300094

An authentication function returned an error.

2300999

Unknown Other Error.

說明

以上錯誤碼的詳細介紹參見HTTP錯誤碼。

HTTP 錯誤碼映射關系:2300000 + curl錯誤碼。更多常用錯誤碼,可參考:curl錯誤碼

示例:

  1. let promise = httpRequest.request("EXAMPLE_URL", {
  2. method: http.RequestMethod.GET,
  3. connectTimeout: 60000,
  4. readTimeout: 60000,
  5. header: {
  6. 'Content-Type': 'application/json'
  7. }
  8. });
  9. promise.then((data) => {
  10. console.info('Result:' + data.result);
  11. console.info('code:' + data.responseCode);
  12. console.info('header:' + JSON.stringify(data.header));
  13. console.info('cookies:' + data.cookies); // 8+
  14. console.info('header.Content-Type:' + data.header['Content-Type']);
  15. console.info('header.Status-Line:' + data.header['Status-Line']);
  16. }).catch((err) => {
  17. console.info('error:' + JSON.stringify(err));
  18. });

destroy

destroy(): void

中斷請求任務。

系統(tǒng)能力:SystemCapability.Communication.NetStack

示例:

  1. httpRequest.destroy();

on('headerReceive')(deprecated)

on(type: 'headerReceive', callback: AsyncCallback<Object>): void

訂閱HTTP Response Header 事件。

說明

此接口已廢棄,建議使用on('headersReceive')8+替代。

系統(tǒng)能力:SystemCapability.Communication.NetStack

參數(shù):

參數(shù)名

類型

必填

說明

type

string

訂閱的事件類型,'headerReceive'。

callback

AsyncCallback<Object>

回調函數(shù)。

示例:

  1. httpRequest.on('headerReceive', (data) => {
  2. console.info('error:' + JSON.stringify(data));
  3. });

off('headerReceive')(deprecated)

off(type: 'headerReceive', callback?: AsyncCallback<Object>): void

取消訂閱HTTP Response Header 事件。

說明
  1. 此接口已廢棄,建議使用off('headersReceive')8+替代。

  2. 可以指定傳入on中的callback取消一個訂閱,也可以不指定callback清空所有訂閱。

系統(tǒng)能力:SystemCapability.Communication.NetStack

參數(shù):

參數(shù)名

類型

必填

說明

type

string

取消訂閱的事件類型,'headerReceive'。

callback

AsyncCallback<Object>

回調函數(shù)。

示例:

  1. httpRequest.off('headerReceive');

on('headersReceive')8+

on(type: 'headersReceive', callback: Callback<Object>): void

訂閱HTTP Response Header 事件。

系統(tǒng)能力:SystemCapability.Communication.NetStack

參數(shù):

參數(shù)名

類型

必填

說明

type

string

訂閱的事件類型:'headersReceive'。

callback

Callback<Object>

回調函數(shù)。

示例:

  1. httpRequest.on('headersReceive', (header) => {
  2. console.info('header: ' + JSON.stringify(header));
  3. });

off('headersReceive')8+

off(type: 'headersReceive', callback?: Callback<Object>): void

取消訂閱HTTP Response Header 事件。

說明

可以指定傳入on中的callback取消一個訂閱,也可以不指定callback清空所有訂閱。

系統(tǒng)能力:SystemCapability.Communication.NetStack

參數(shù):

參數(shù)名

類型

必填

說明

type

string

取消訂閱的事件類型:'headersReceive'。

callback

Callback<Object>

回調函數(shù)。

示例:

  1. httpRequest.off('headersReceive');

once('headersReceive')8+

once(type: 'headersReceive', callback: Callback<Object>): void

訂閱HTTP Response Header 事件,但是只觸發(fā)一次。一旦觸發(fā)之后,訂閱器就會被移除。使用callback方式作為異步方法。

系統(tǒng)能力:SystemCapability.Communication.NetStack

參數(shù):

參數(shù)名

類型

必填

說明

type

string

訂閱的事件類型:'headersReceive'。

callback

Callback<Object>

回調函數(shù)。

示例:

  1. httpRequest.once('headersReceive', (header) => {
  2. console.info('header: ' + JSON.stringify(header));
  3. });

HttpRequestOptions

發(fā)起請求可選參數(shù)的類型和取值范圍。

系統(tǒng)能力:以下各項對應的系統(tǒng)能力均為SystemCapability.Communication.NetStack。

名稱

類型

必填

說明

method

RequestMethod

請求方式。

extraData

string | Object | ArrayBuffer8+

發(fā)送請求的額外數(shù)據(jù)。

- 當HTTP請求為POST、PUT等方法時,此字段為HTTP請求的content。當'Content-Type'為'application/x-www-form-urlencoded'時,請求提交的信息主體數(shù)據(jù)應在key和value進行URL轉碼后按照鍵值對"key1=value1&key2=value2&key3=value3"的方式進行編碼。

- 當HTTP請求為GET、OPTIONS、DELETE、TRACE、CONNECT等方法時,此字段為HTTP請求的參數(shù)補充,參數(shù)內容會拼接到URL中進行發(fā)送。

- 開發(fā)者傳入string對象,開發(fā)者需要自行編碼,將編碼后的string傳入。

expectDataType9+

HttpDataType

指定返回數(shù)據(jù)的類型。如果設置了此參數(shù),系統(tǒng)將優(yōu)先返回指定的類型。

usingCache9+

boolean

是否使用緩存,默認為true。

priority9+

number

優(yōu)先級,范圍[1,1000],默認是1。

header

Object

HTTP請求頭字段。默認{'Content-Type': 'application/json'}。

readTimeout

number

讀取超時時間。單位為毫秒(ms),默認為60000ms。

設置為0表示不會出現(xiàn)超時情況。

connectTimeout

number

連接超時時間。單位為毫秒(ms),默認為60000ms。

usingProtocol9+

HttpProtocol

使用協(xié)議。默認值由系統(tǒng)自動指定。

RequestMethod

HTTP 請求方法。

系統(tǒng)能力:以下各項對應的系統(tǒng)能力均為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。

ResponseCode

發(fā)起請求返回的響應碼。

系統(tǒng)能力:以下各項對應的系統(tǒng)能力均為SystemCapability.Communication.NetStack。

名稱

說明

OK

200

請求成功。一般用于GET與POST請求。

CREATED

201

已創(chuàng)建。成功請求并創(chuàng)建了新的資源。

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

服務器理解請求客戶端的請求,但是拒絕執(zhí)行此請求。

NOT_FOUND

404

服務器無法根據(jù)客戶端的請求找到資源(網(wǎng)頁)。

BAD_METHOD

405

客戶端請求中的方法被禁止。

NOT_ACCEPTABLE

406

服務器無法根據(jù)客戶端請求的內容特性完成請求。

PROXY_AUTH

407

請求要求代理的身份認證。

CLIENT_TIMEOUT

408

請求時間過長,超時。

CONFLICT

409

服務器完成客戶端的PUT請求是可能返回此代碼,服務器處理請求時發(fā)生了沖突。

GONE

410

客戶端請求的資源已經不存在。

LENGTH_REQUIRED

411

服務器無法處理客戶端發(fā)送的不帶Content-Length的請求信息。

PRECON_FAILED

412

客戶端請求信息的先決條件錯誤。

ENTITY_TOO_LARGE

413

由于請求的實體過大,服務器無法處理,因此拒絕請求。

REQ_TOO_LONG

414

請求的URI過長(URI通常為網(wǎng)址),服務器無法處理。

UNSUPPORTED_TYPE

415

服務器無法處理請求的格式。

INTERNAL_ERROR

500

服務器內部錯誤,無法完成請求。

NOT_IMPLEMENTED

501

服務器不支持請求的功能,無法完成請求。

BAD_GATEWAY

502

充當網(wǎng)關或代理的服務器,從遠端服務器接收到了一個無效的請求。

UNAVAILABLE

503

由于超載或系統(tǒng)維護,服務器暫時的無法處理客戶端的請求。

GATEWAY_TIMEOUT

504

充當網(wǎng)關或代理的服務器,未及時從遠端服務器獲取請求。

VERSION

505

服務器請求的HTTP協(xié)議的版本。

HttpResponse

request方法回調函數(shù)的返回值類型。

系統(tǒng)能力:以下各項對應的系統(tǒng)能力均為SystemCapability.Communication.NetStack。

名稱

類型

必填

說明

result

string | Object | ArrayBuffer6+

HTTP請求根據(jù)響應頭中Content-type類型返回對應的響應格式內容:

- application/json:返回JSON格式的字符串,如需HTTP響應具體內容,需開發(fā)者自行解析

- application/octet-stream:ArrayBuffer

- 其他:string

resultType9+

HttpDataType

返回值類型。

responseCode

ResponseCode | number

回調函數(shù)執(zhí)行成功時,此字段為ResponseCode。若執(zhí)行失敗,錯誤碼將會從AsyncCallback中的err字段返回。

header

Object

發(fā)起HTTP請求返回來的響應頭。當前返回的是JSON格式字符串,如需具體字段內容,需開發(fā)者自行解析。常見字段及解析方式如下:

- Content-Type:header['Content-Type'];

- Status-Line:header['Status-Line'];

- Date:header.Date/header['Date'];

- Server:header.Server/header['Server'];

cookies8+

string

服務器返回的 cookies。

http.createHttpResponseCache9+

createHttpResponseCache(cacheSize?: number): HttpResponseCache

創(chuàng)建一個默認的對象來存儲HTTP訪問請求的響應。

系統(tǒng)能力:SystemCapability.Communication.NetStack

參數(shù):

參數(shù)名

類型

必填

說明

cacheSize

number

緩存大小最大為10*1024*1024(10MB),默認最大。

返回值:

類型

說明

HttpResponseCache

返回一個存儲HTTP訪問請求響應的對象。

示例:

  1. import http from '@ohos.net.http';
  2. let httpResponseCache = http.createHttpResponseCache();

HttpResponseCache9+

存儲HTTP訪問請求響應的對象。在調用HttpResponseCache的方法前,需要先通過createHttpResponseCache()創(chuàng)建一個任務。

flush9+

flush(callback: AsyncCallback<void>): void

將緩存中的數(shù)據(jù)寫入文件系統(tǒng),以便在下一個HTTP請求中訪問所有緩存數(shù)據(jù),使用callback方式作為異步方法。

系統(tǒng)能力:SystemCapability.Communication.NetStack

參數(shù):

參數(shù)名

類型

必填

說明

callback

AsyncCallback<void>

回調函數(shù)返回寫入結果。

示例:

  1. httpResponseCache.flush(err => {
  2. if (err) {
  3. console.info('flush fail');
  4. return;
  5. }
  6. console.info('flush success');
  7. });

flush9+

flush(): Promise<void>

將緩存中的數(shù)據(jù)寫入文件系統(tǒng),以便在下一個HTTP請求中訪問所有緩存數(shù)據(jù),使用Promise方式作為異步方法。

系統(tǒng)能力:SystemCapability.Communication.NetStack

返回值:

類型

說明

Promise<void>

以Promise形式返回寫入結果。

示例:

  1. httpResponseCache.flush().then(() => {
  2. console.info('flush success');
  3. }).catch(err => {
  4. console.info('flush fail');
  5. });

delete9+

delete(callback: AsyncCallback<void>): void

禁用緩存并刪除其中的數(shù)據(jù),使用callback方式作為異步方法。

系統(tǒng)能力:SystemCapability.Communication.NetStack

參數(shù):

參數(shù)名

類型

必填

說明

callback

AsyncCallback<void>

回調函數(shù)返回刪除結果。

示例:

  1. httpResponseCache.delete(err => {
  2. if (err) {
  3. console.info('delete fail');
  4. return;
  5. }
  6. console.info('delete success');
  7. });

delete9+

delete(): Promise<void>

禁用緩存并刪除其中的數(shù)據(jù),使用Promise方式作為異步方法。

系統(tǒng)能力:SystemCapability.Communication.NetStack

返回值:

類型

說明

Promise<void>

以Promise形式返回刪除結果。

示例:

  1. httpResponseCache.delete().then(() => {
  2. console.info('delete success');
  3. }).catch(err => {
  4. console.info('delete fail');
  5. });

HttpDataType9+

http的數(shù)據(jù)類型。

系統(tǒng)能力:SystemCapability.Communication.NetStack

名稱

說明

STRING

0

字符串類型。

OBJECT

1

對象類型。

ARRAY_BUFFER

2

二進制數(shù)組類型。

HttpProtocol9+

http協(xié)議版本。

系統(tǒng)能力:SystemCapability.Communication.NetStack

名稱

說明

HTTP1_1

協(xié)議http1.1

HTTP2

協(xié)議http2

以上內容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號