当前位置: 首页 > news >正文

HarmonyOs开发之———使用HTTP访问网络资源

 谢谢关注!!

前言:上一篇文章主要介绍HarmonyOs开发之———Video组件的使用:HarmonyOs开发之———Video组件的使用_华为 video标签查看-CSDN博客

HarmonyOS 网络开发入门:使用 HTTP 访问网络资源

HarmonyOS 作为新一代智能终端操作系统,提供了丰富的网络 API 支持。本文将详细介绍如何在 HarmonyOS 应用中使用 HTTP 协议访问网络资源,包含完整的开发流程和示例代码。

一、网络权限配置

在使用 HTTP 网络请求前,需要在应用配置文件中声明网络访问权限。打开项目中的config.json文件,添加以下权限声明:

{"module": {"reqPermissions": [{"name": "ohos.permission.INTERNET","reason": "需要访问网络获取数据","usedScene": {"ability": ["com.example.myapplication.MainAbility"],"when": "always"}}]}
}
二、使用 HttpURLConnection 进行 HTTP 请求

HarmonyOS 提供了标准 Java API 兼容的HttpURLConnection类,以下是使用该类进行 GET 和 POST 请求的示例:

import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import ohos.eventhandler.InnerEvent;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;public class NetworkAbility extends Ability {private static final int MSG_SUCCESS = 1;private static final int MSG_ERROR = 2;private EventHandler mainHandler;@Overridepublic void onStart(Intent intent) {super.onStart(intent);// 创建主线程的EventHandler用于UI更新mainHandler = new EventHandler(EventRunner.getMainEventRunner()) {@Overrideprotected void processEvent(InnerEvent event) {super.processEvent(event);switch (event.eventId) {case MSG_SUCCESS:String result = (String) event.object;// 处理成功返回的数据break;case MSG_ERROR:String errorMsg = (String) event.object;// 处理错误信息break;}}};// 示例:发起GET请求getRequest("https://api.example.com/data");// 示例:发起POST请求Map<String, String> params = new HashMap<>();params.put("username", "test");params.put("password", "123456");postRequest("https://api.example.com/login", params);}/*** 发起GET请求*/private void getRequest(String urlStr) {new Thread(() -> {HttpURLConnection connection = null;BufferedReader reader = null;try {URL url = new URL(urlStr);connection = (HttpURLConnection) url.openConnection();connection.setRequestMethod("GET");connection.setConnectTimeout(5000);connection.setReadTimeout(5000);int responseCode = connection.getResponseCode();if (responseCode == HttpURLConnection.HTTP_OK) {InputStream inputStream = connection.getInputStream();reader = new BufferedReader(new InputStreamReader(inputStream));StringBuilder response = new StringBuilder();String line;while ((line = reader.readLine()) != null) {response.append(line);}// 发送成功消息到主线程mainHandler.sendEvent(InnerEvent.get(MSG_SUCCESS, response.toString()));} else {mainHandler.sendEvent(InnerEvent.get(MSG_ERROR, "HTTP错误: " + responseCode));}} catch (Exception e) {mainHandler.sendEvent(InnerEvent.get(MSG_ERROR, "请求异常: " + e.getMessage()));} finally {// 关闭资源if (reader != null) {try {reader.close();} catch (IOException e) {e.printStackTrace();}}if (connection != null) {connection.disconnect();}}}).start();}/*** 发起POST请求*/private void postRequest(String urlStr, Map<String, String> params) {new Thread(() -> {HttpURLConnection connection = null;OutputStream outputStream = null;BufferedReader reader = null;try {URL url = new URL(urlStr);connection = (HttpURLConnection) url.openConnection();connection.setRequestMethod("POST");connection.setConnectTimeout(5000);connection.setReadTimeout(5000);connection.setDoOutput(true);connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");// 构建POST参数StringBuilder postData = new StringBuilder();for (Map.Entry<String, String> param : params.entrySet()) {if (postData.length() != 0) postData.append('&');postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));postData.append('=');postData.append(URLEncoder.encode(param.getValue(), "UTF-8"));}byte[] postDataBytes = postData.toString().getBytes("UTF-8");// 写入POST数据outputStream = connection.getOutputStream();outputStream.write(postDataBytes);int responseCode = connection.getResponseCode();if (responseCode == HttpURLConnection.HTTP_OK) {InputStream inputStream = connection.getInputStream();reader = new BufferedReader(new InputStreamReader(inputStream));StringBuilder response = new StringBuilder();String line;while ((line = reader.readLine()) != null) {response.append(line);}mainHandler.sendEvent(InnerEvent.get(MSG_SUCCESS, response.toString()));} else {mainHandler.sendEvent(InnerEvent.get(MSG_ERROR, "HTTP错误: " + responseCode));}} catch (Exception e) {mainHandler.sendEvent(InnerEvent.get(MSG_ERROR, "请求异常: " + e.getMessage()));} finally {// 关闭资源if (outputStream != null) {try {outputStream.close();} catch (IOException e) {e.printStackTrace();}}if (reader != null) {try {reader.close();} catch (IOException e) {e.printStackTrace();}}if (connection != null) {connection.disconnect();}}}).start();}
}
三、网络请求注意事项
  1. 线程管理:HarmonyOS 不允许在主线程中进行网络操作,必须在子线程中执行网络请求。示例中使用了 Thread+EventHandler 的方式,实际开发中也可以使用 AsyncTask 或线程池。
  2. 异常处理:网络请求可能会因为各种原因失败,如网络中断、服务器错误等,必须进行完善的异常处理。
  3. 数据解析:接收到的网络数据通常需要解析,常见的格式有 JSON、XML 等。可以使用 GSON、FastJSON 等库进行 JSON 数据解析。
  4. HTTPS 支持:如果需要访问 HTTPS 资源,还需要处理 SSL 证书验证等问题。
四、使用 OkHttp 库简化网络请求

除了标准的 HttpURLConnection,也可以使用第三方库 OkHttp 来简化网络请求。首先需要在build.gradle中添加依赖:

dependencies {implementation 'com.squareup.okhttp3:okhttp:4.9.1'}

以下是使用 OkHttp 的示例代码:

// 在Ability中调用
public void fetchData() {OkHttpUtil.get("https://api.example.com/data", new Callback() {@Overridepublic void onFailure(Call call, IOException e) {// 处理失败mainHandler.sendEvent(InnerEvent.get(MSG_ERROR, "请求失败: " + e.getMessage()));}@Overridepublic void onResponse(Call call, Response response) throws IOException {if (response.isSuccessful()) {String responseData = response.body().string();// 发送成功消息到主线程mainHandler.sendEvent(InnerEvent.get(MSG_SUCCESS, responseData));} else {mainHandler.sendEvent(InnerEvent.get(MSG_ERROR, "响应错误: " + response.code()));}}});
}

使用 OkHttp 发起请求的示例:

// 在Ability中调用
public void fetchData() {OkHttpUtil.get("https://api.example.com/data", new Callback() {@Overridepublic void onFailure(Call call, IOException e) {// 处理失败mainHandler.sendEvent(InnerEvent.get(MSG_ERROR, "请求失败: " + e.getMessage()));}@Overridepublic void onResponse(Call call, Response response) throws IOException {if (response.isSuccessful()) {String responseData = response.body().string();// 发送成功消息到主线程mainHandler.sendEvent(InnerEvent.get(MSG_SUCCESS, responseData));} else {mainHandler.sendEvent(InnerEvent.get(MSG_ERROR, "响应错误: " + response.code()));}}});
}

五、总结

本文介绍了 HarmonyOS 中使用 HTTP 协议访问网络资源的基本方法,包括权限配置、使用 HttpURLConnection 和 OkHttp 进行网络请求的实现。在实际开发中,建议根据项目需求选择合适的网络请求方式,并注意网络请求的线程管理和异常处理,以提供稳定、流畅的用户体验。

近期因个人原因停更感到非常抱歉。之后会每周分享希望大家喜欢。

请注意,HarmonyOS的UI框架可能会随着版本的更新而有所变化,因此为了获取最新和最准确的属性说明和用法,建议查阅HarmonyOS的官方文档。

如需了解更多请联系博主,本篇完。

下一篇:HarmonyOs开发之———UIAbility进阶
HarmonyOs开发,学习专栏敬请试读订阅:https://blog.csdn.net/this_is_bug/category_12556429.html?fromshare=blogcolumn&sharetype=blogcolumn&sharerId=12556429&sharerefer=PC&sharesource=this_is_bug&sharefrom=from_link
谢谢阅读,烦请关注:

后续将持续更新!!

相关文章:

  • 【Vue 3 + Vue Router 4】如何正确重置路由实例(resetRouter)——避免“VueRouter is not defined”错误
  • 前端面试每日三题 - Day 34
  • 【SSL部署与优化​】​​TLS 1.3的核心改进与性能优化​​
  • 模态参数识别中的特征实现算法
  • 嵌入式自学第二十一天(5.14)
  • 如何利用大模型对文章进行分段,提高向量搜索的准确性?
  • PyTorch 的自动微分和动态计算图
  • 信息化项目绩效管理办法V5.0
  • Seed1.5-VL:高效通用的视觉-语言基础模型
  • 基于 TensorFlow 框架的联邦学习可穿戴设备健康数据个性化健康管理平台研究
  • 单片机-STM32部分:14、SPI
  • 【计算机视觉】OpenCV实战项目:Face-Mask-Detection 项目深度解析:基于深度学习的口罩检测系统
  • 自然语言处理入门级项目——文本分类
  • MQTT 在Spring Boot 中的使用
  • Oracle — PL-SQL
  • 使用深度学习预训练模型检测物体
  • lesson01-PyTorch初见(理论+代码实战)
  • 在线黑白图像转换:简单却强大的视觉表达工具
  • Java生成可控的Word表格功能开发
  • hudi + flinksql 处理 金额汇总的实时场景
  • 人民网三评“网络烂梗”:莫让低级趣味围猎青少年
  • 坚持吃素,是不是就不会得高血脂了?
  • “中国神湖”加快放大资源规模!3亿美元换海外年产380万吨钾盐项目
  • 外交部:反对美方人士发表不负责任谬论
  • “80后”德州市接待事务中心副主任刘巍“拟进一步使用”
  • 媒体:“西北大学副校长范代娣成陕西首富”系乌龙,但她的人生如同开挂