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, readTimeout: 30000 });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 }
);
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": {"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};
}