harmony OS NEXT- HTTP 模块笔记
harmony OS NEXT- HTTP 模块笔记
1.基础请求流程
1.1 模块初始化
import http from '@ohos.net.http';
// 创建请求实例(支持连接池复用)
const httpRequest = http.createHttp();
1.2 GET请求基础模板
async function fetchData(url: string): Promise<string> {
try {
const response = await httpRequest.request(
url,
{
method: http.RequestMethod.GET,
header: {
'Content-Type': 'application/json',
'User-Agent': 'MyHarmonyApp/1.0.0'
},
connectTimeout: 15000, // 15秒连接超时
readTimeout: 30000 // 30秒读取超时
}
);
if (response.responseCode === http.ResponseCode.OK) {
return response.result.toString();
} else {
throw new Error(`HTTP Error: ${response.responseCode}`);
}
} catch (error) {
console.error(`Network request failed: ${error.code} - ${error.message}`);
throw error;
} finally {
httpRequest.destroy(); // 释放连接资源
}
}
2.进阶请求配置
2.1 多参数POST请求
const postData = {
username: 'user123',
password: 's3cr3tP@ss',
deviceId: deviceInfo.deviceId // 获取设备信息
};
const response = await httpRequest.request(
'https://api.example.com/login',
{
method: http.RequestMethod.POST,
header: {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Basic ' + base64.encode('client:secret')
},
extraData: httpRequest.stringifyParameters(postData),
expectDataType: http.HttpDataType.OBJECT // 自动反序列化JSON
}
);
2.2 文件上传
const filePath = 'data/storage/files/image.jpg';
const file = await fileIo.open(filePath, fileIo.OpenMode.READ_ONLY);
const response = await httpRequest.upload(
'https://upload.example.com',
{
files: [
{
filename: 'avatar.jpg',
name: 'file',
uri: `internal://app/${filePath}`,
type: 'image/jpeg'
}
],
data: [
{
name: 'description',
value: 'Profile photo'
}
]
},
{
method: http.RequestMethod.PUT
}
);
3. 网络权限声明
// module.json5
{
"module": {
"requestPermissions": [
{
"name": "ohos.permission.INTERNET",
"reason": "Required for network access"
},
{
"name": "ohos.permission.GET_NETWORK_INFO",
"reason": "Check network connectivity"
}
]
}
}
4.数据解析技巧
4.1 JSON自动解析
{
// 在请求配置中设置:
expectDataType: http.HttpDataType.OBJECT
}
// 直接获取结构化数据
const userData = response.result as User;
4.2 XML转换
import convert from 'xml-js';
const xmlText = await response.result.toString();
const jsonData = convert.xml2json(xmlText, {
compact: true,
spaces: 2
});
5.实战案例:天气预报应用
interface WeatherData {
city: string;
temperature: number;
humidity: number;
condition: string;
}
async function getWeather(cityId: string): Promise<WeatherData> {
const apiUrl = `https://api.weather.com/v3/wx/forecast?city=${cityId}&format=json`;
const response = await httpRequest.request(apiUrl, {
headers: {
'x-api-key': 'your_api_key_here'
}
});
return {
city: response.result.location.city,
temperature: response.result.current.temp,
humidity: response.result.current.humidity,
condition: response.result.current.phrase
};
}
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.dtcms.com/a/102394.html
如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!