在使用app的時候,不可能將所有信息都存儲在app中,是需要鏈接互聯網,從服務端獲取數據。
使用HTTP訪問網絡
HTTP即超文本傳輸協議(Hyper Text Transfer Protocol,HTTP)是一個簡單的請求-響應協議。它指定了客戶端可能發送給服務器什么樣的消息以及得到什么樣的響應。
在ArkTs中我們使用http的流程大致如下:
導入http模塊
import http from '@ohos.net.http'
除了導入http模塊,還需要中module.json5中添加網絡訪問權限
{"module" : {"requestPermissions":[{"name": "ohos.permission.INTERNET"}]}
}
創建http請求
適應createHttp()創建一個httpRequest對象。
每一個httpRequest對象對應一個http請求任務,不可服用
import http from '@ohos.net.http';
let httpRequest = http.createHttp();
訂閱請求頭
用于訂閱http響應頭,此接口會比request請求先返回,可以根據業務需要訂閱此消息
import http from '@ohos.net.http';
let httpRequest = http.createHttp();
httpRequest.on('headersReceive', (header) => {console.info('header: ' + JSON.stringify(header));
});
發起請求
通過發起請求,向服務器請求數據
http支持的請求方式
方法 | 說明 |
---|---|
OPTIONS | HTTP 請求 OPTIONS |
GET | HTTP 請求 GET |
HEAD | HTTP 請求 HEAD |
POST | HTTP 請求 POST |
PUT | HTTP 請求 PUT |
DELETE | HTTP 請求 DELETE |
TRACE | HTTP 請求 TRACE |
CONNECT | HTTP 請求 CONNECT |
- get 方法
let promise = httpRequest.request("EXAMPLE_URL", {method: http.RequestMethod.GET,connectTimeout: 60000,readTimeout: 60000,header: {'Content-Type': 'application/json'}
});
- post 方法
let promise = httpRequest.request("EXAMPLE_URL", {method: http.RequestMethod.GET,connectTimeout: 60000,readTimeout: 60000,extraData:{// 數據部分},header: {'Content-Type': 'application/json'}
});
處理響應
let promise = httpRequest.request("EXAMPLE_URL", {method: http.RequestMethod.GET,connectTimeout: 60000,readTimeout: 60000,extraData:{// 數據部分},header: {'Content-Type': 'application/json'}
});
promise.then((res)=>{})
返回的參數類型是:HttpResponse
HttpResponse 參數
參數 | 類型 | 必填 | 說明 |
---|---|---|---|
result | string \Object \ArrayBuffer8+ | 是 | Http請求根據響應頭中Content-type類型返回對應的響應格式內容:application/json:返回JSON格式的字符串,如需Http響應具體內容,需開發者自行解析;application/octet-stream:ArrayBuffer;其他:string |
responseCode | ResponseCode \number | 是 | 回調函數執行成功時,此字段為ResponseCode。若執行失敗,錯誤碼將會從AsyncCallback中的err字段返回。錯誤碼如下:; 200:通用錯誤; 202:參數錯誤; 300:I/O錯誤 |
header | Object | 是 | 發起http請求返回來的響應頭。當前返回的是JSON格式字符串,如需具體字段內容,需開發者自行解析。常見字段及解析方式如下:Content-Type:header[‘Content-Type’];Status-Line:header[‘Status-Line’];Date:header.Date/header[‘Date’];Server:header.Server/header[‘Server’]; |
cookies8+ | Array | 是 | 服務器返回的 cookies。 |