一、代码示例
const inDevelopmentMode = true
// 测试服地址
const debugUrl = 'https://www.test.com/'
// 正式服地址
const releaseUrl = 'https://www.example.com/'
const BASE_URL = inDevelopmentMode ? debugUrl : releaseUrl
// 引入包名
import http from '@ohos.net.http'
const initHeader = {
'Content-Type': 'application/json'
}
const initOtherOptions = {
expectDataType: http.HttpDataType.STRING, // 可选,指定返回数据的类型
usingCache: true, // 可选,默认为true
priority: 1, // 可选,默认为1
connectTimeout: 60000, // 可选,默认为60000ms
readTimeout: 60000, // 可选,默认为60000ms
usingProtocol: http.HttpProtocol.HTTP1_1 // 可选,协议类型默认值由系统自动指定
}
export function request<T>(requestOptions: T) {
}
['get', 'post', 'put', 'delete', 'patch'].forEach(item => {
request[item] = (requestOptions) => {
const { url, method = 'GET', data = {}, params = {}, headers = initHeader, otherOptions = initOtherOptions } = requestOptions
const _method = method.toUpperCase()
return sendRequest(url, _method, data, params, headers, otherOptions)
}
})
function sendRequest<T>(url: string, method: string, data?: T, params?: T, headers?: T, otherOptions?: T) {
console.log('URL:', url)
console.log('Data:', JSON.stringify(data))
console.log('Params', JSON.stringify(params))
let _url = BASE_URL + url
if (params && Object.keys(params).length > 0) {
_url = _url + '?' + Object.keys(params).map(key => key + '=' + params[key]).join('&')
}
// 每一个httpRequest对应一个HTTP请求任务,不可复用
const httpRequest = http.createHttp()
// 用于订阅HTTP响应头,此接口会比request请求先返回。可以根据业务需要订阅此消息
// 从API 8开始,使用on('headersReceive', Callback)替代on('headerReceive', AsyncCallback)。
httpRequest.on('headersReceive', (header) => {
console.info('header: ' + JSON.stringify(header))
})
return new Promise((resolve, reject) => {
httpRequest.request(_url, {
method: http.RequestMethod[method],
header: headers,
extraData: data,
...otherOptions
}).then((data) => {
// data.header为HTTP响应头,可根据业务需要进行解析
console.log('header:' + JSON.stringify(data.header))
console.log('cookies:' + JSON.stringify(data.cookies)) // 8+
// data.result为HTTP响应内容,可根据业务需要进行解析
console.info('Result:' + JSON.stringify(data.result))
console.info('code:' + JSON.stringify(data.responseCode))
resolve(data)
}).catch((error) => {
console.info('error:' + JSON.stringify(error))
reject(error)
}).finally(() => {
httpRequest.off('headersReceive')
// 当该请求使用完毕时,调用destroy方法主动销毁
httpRequest.destroy()
})
})
}
二、使用方式
在文件引入后,可以通过request.get、request.post、request.put…… 这些方式调用
在ets文件中
import {request} from "entry/src/util/request"
...
Button('点击').fontSize(20).onClick(async()=>{
const res = await request.get({
url:'search',
params:{
wd:'你好'
}
})
console.log('*****',JSON.stringify(res))
})
...
三、学习指引
从上面代码上看,其实harmonyos应用和普通前端应用开发方式有很多相同的地方,虽然CSS采用了链式调用的方式去替换,但是从逻辑代码和编码方式来说,都是非常相近的
harmonyos应用使用ArkTs开发,在TypeScript的基础上,匹配ArkUI框架,扩展了声明式UI、状态管理等相应的能力,对前端来说,非常好上手
而且已经准备好了学习地图 华为云学堂,还有随堂考试来检测学习效果哦