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

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
谢谢阅读,烦请关注:

后续将持续更新!!

http://www.xdnf.cn/news/6011.html

相关文章:

  • Eslint和perrier的作用
  • CSS盒子模型:Padding与Margin的适用场景与注意事项
  • npm 报错 gyp verb `which` failed Error: not found: python2 解决方案
  • 【漫话机器学习系列】259.神经网络参数的初始化(Initialization Of Neural Network Parameters)
  • 【Java面试题】——this 和 super 的区别
  • PHP黑白胶卷底片图转彩图功能 V2025.05.15
  • Stable Diffusion WebUI 插件大全:功能详解与下载地址
  • 【软件测试】:推荐一些接口与自动化测试学习练习网站(API测试与自动化学习全攻略)
  • 配置Nginx解决http host头攻击漏洞【详细步骤】
  • Dockerfile实战:从零构建自定义CentOS镜像
  • Python爬虫实战:研究进制流数据,实现逆向解密
  • 【优选算法 | 字符串】字符串模拟题精选:思维+实现解析
  • 【python实用小脚本-59】连续刷题7天,手动整理编程题目效率低下,Python代码5分钟搞定,效率提升80%(附方案)
  • 力扣刷题Day 48:盛最多水的容器(283)
  • Linux操作系统中的SOCKET相关 - Socket字节序调整与网络传输
  • Kubernetes 标签和注解
  • 【软件测试】第一章·软件测试概述
  • 行动算子(知识)
  • GZip+Base64压缩字符串在ios上解压报错问题解决(安卓、PC模拟器正常)
  • 服务器中存储空间不足该怎么办?
  • IP协议的特性
  • 大白话解释联邦学习
  • skolelinux系统详解
  • Proxmox VE 8.4.0显卡直通完整指南:NVIDIA Tesla T4 实战
  • 什么是懒加载?
  • 06_java常见集合类底层实现
  • unity 制作某个旋转动画
  • 分割一切(SAM) 论文阅读:Segment Anything
  • 用vue和go实现登录加密
  • 科研领域开源情报应用:从全球信息网络到创新决策