第一步:在module.json中添加权限
"requestPermissions": [
{
"name": "ohos.permission.INTERNET",
}
]
第二步:实现网络请求工具类
import http from '@ohos.net.http'
class HttpModel {
baseUrl: string = 'https://blog.csdn.net/weixin_71403100/article/details/136195958'
reqHttp():Promise<string> {
return new Promise((resolve, reject) => {
//1.创建http请求
let httpRequest = http.createHttp()
//2.发送请求
httpRequest.request(
`${this.baseUrl}`,
{
method: http.RequestMethod.POST,
// extraData: { 'username': 'admin', 'password': 'admin' },
header: {
'X-Tenant-ID': '1',
'Content-Type': 'application/json'
},
connectTimeout: 10000,
readTimeout: 10000
},
).then(resp => {
if (resp.responseCode === 200) {
//查询成功
console.log('http--成功', resp.result)
resolve(JSON.parse(resp.result.toString()))
return resp.result
} else {
console.log('http--失败', resp.result)
reject('查询失败')
return resp.result
}
})
.catch(error => {
console.info('error:' + JSON.stringify(error))
reject('查询失败')
return '查询失败'
})
})
}
}
const httpModel = new HttpModel()
export default httpModel as HttpModel
第三步:实现网络请求调用
import HttpModel from '../moudle/HttpModel'
import webview from '@ohos.web.webview';
@Entry
@Component
struct Index {
controller: webview.WebviewController = new webview.WebviewController();
aboutToAppear(): void {
// 配置Web开启调试模式
webview.WebviewController.setWebDebuggingAccess(true);
}
build() {
Column() {
Button('网络请求').onClick(() => {
HttpModel.reqHttp()
}).width('80%')
.margin(10)
Web({ src: 'https://blog.csdn.net/weixin_71403100/article/details/136195958', controller: this.controller })
.height(100)
}
.height('100%')
.width('100%')
}
}
补充特殊情况使用:
//请求头格式
header: {
'Content-Type': 'application/x-www-form-urlencoded',
}
//转成url编码
let toServerJson = {
"cipher": "775E7375E9415817A6F6E79C517198C8A2F0B799EEC823",
"keyI": "0",
"remark": "",
"sign": "979BD364B643D1569748ECD1E2A74B8BE"
}
// 将 JSON 对象转换为字符串
const jsonString = JSON.stringify(toServerJson);
// 对字符串进行 URL 编码
const urlEncodedString = encodeURIComponent(jsonString);
//参数拼接
extraData: "data=" + urlEncodedString,