您的位置:首页 > 娱乐 > 明星 > 网页设计实训报告2000字_免费咨询医生软件_网页设计与制作书籍_国际军事新闻最新消息视频

网页设计实训报告2000字_免费咨询医生软件_网页设计与制作书籍_国际军事新闻最新消息视频

2025/6/28 22:02:14 来源:https://blog.csdn.net/Yihong1833100198/article/details/146889716  浏览:    关键词:网页设计实训报告2000字_免费咨询医生软件_网页设计与制作书籍_国际军事新闻最新消息视频
网页设计实训报告2000字_免费咨询医生软件_网页设计与制作书籍_国际军事新闻最新消息视频

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};
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com