httpclient插件在天气预报应用中的应用
在开发一款OpenHarmony平台的天气预报应用时,需要实现从天气API获取数据、下载天气图标以及管理网络请求等功能。httpclient插件凭借其高效性和丰富功能成为首选解决方案。
核心功能实现

  1. 基础配置

import { HttpClient, TimeUnit, Request } from ‘@ohos/httpclient’;

// 初始化HttpClient
private weatherClient = new HttpClient.Builder()
.setConnectTimeout(15, TimeUnit.SECONDS)
.setReadTimeout(15, TimeUnit.SECONDS)
.addInterceptor(new WeatherAuthInterceptor()) // 自定义认证拦截器
.build();

// 在module.json5中添加权限
“requestPermissions”: [
{
“name”: “ohos.permission.INTERNET”
},
{
“name”: “ohos.permission.GET_NETWORK_INFO”
}
]
2. 获取天气数据(GET请求)

async fetchWeatherData(city: string): Promise {
try {
const request = new Request.Builder()
.get(https://api.weather.com/v3?city=${city})
.addHeader(“Accept”, “application/json”)
.tag(city_${city}) // 为请求添加城市标签
.build();

const response = await this.weatherClient.newCall(request).execute();

if (response.responseCode === 200) {
  return JSON.parse(response.result) as WeatherData;
} else {
  throw new Error(`天气请求失败: ${response.responseCode}`);
}

} catch (error) {
Logger.error(天气数据获取失败: ${error.message});
throw error;
}
}
3. 下载天气图标(文件下载)

async downloadWeatherIcon(iconUrl: string): Promise {
const context = getContext(this);
const iconPath = ${context.filesDir}/weather_icons/${Date.now()}.png;

const request = new Request.Builder()
.download(iconUrl, iconPath)
.setAbilityContext(context)
.build();

const downloadTask = await this.weatherClient.newCall(request).execute();

// 进度监听
downloadTask.downloadTask.on(‘progress’, (received, total) => {
const progress = Math.floor((received / total) * 100);
AppStorage.setOrCreate(‘downloadProgress’, progress);
});

// 返回本地路径
return new Promise((resolve, reject) => {
downloadTask.downloadTask.on(‘complete’, () => {
resolve(iconPath);
});
downloadTask.downloadTask.on(‘error’, (err) => {
reject(图标下载失败: ${err.message});
});
});
}
4. 城市切换时的请求管理

// 取消当前城市的请求
cancelCityRequest(city: string) {
this.weatherClient.cancelRequestByTag(city_${city});
Logger.info(已取消 ${city} 的天气请求);
}

// 切换城市时调用
changeCity(newCity: string) {
this.cancelCityRequest(this.currentCity);
this.fetchWeatherData(newCity).then(data => {
this.updateWeatherDisplay(data);
});
}
5. 自定义拦截器(添加API密钥)

import { Interceptor, Chain, Request } from ‘@ohos/httpclient’;

class WeatherAuthInterceptor implements Interceptor {
intercept(chain: Chain): Promise {
const originalRequest: Request = chain.request();

// 添加认证参数
const authedRequest = originalRequest.newBuilder()
  .addQueryParam("apikey", WEATHER_API_KEY)
  .build();

return chain.proceed(authedRequest);

}
}
项目优势与经验
性能优化:

全局HttpClient实例减少重复配置

响应缓存减少网络请求

自动GZIP解压缩节省流量

稳定性保障:

// 证书锁定防止中间人攻击
.certificates([this.weatherCertData])
错误处理增强:

// 统一错误处理
this.weatherClient.setGlobalErrorHandler((error) => {
Logger.error(网络请求异常: ${error.code} - ${error.data});
promptAction.showToast({ message: “网络连接异常” });
});
高级特性应用:

请求优先级设置:关键数据请求设为HIGH优先级

连接池优化:复用连接提升性能

超时重试机制:增强弱网环境稳定性

Logo

社区规范:仅讨论OpenHarmony相关问题。

更多推荐