HarmonyOs开发之———使用HTTP访问网络资源_ohos.permission.internet
谢谢关注!!
前言:上一篇文章主要介绍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; @Override public void onStart(Intent intent) { super.onStart(intent); // 创建主线程的EventHandler用于UI更新 mainHandler = new EventHandler(EventRunner.getMainEventRunner()) { @Override protected 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 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 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 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(); }}
三、网络请求注意事项
- 线程管理:HarmonyOS 不允许在主线程中进行网络操作,必须在子线程中执行网络请求。示例中使用了 Thread+EventHandler 的方式,实际开发中也可以使用 AsyncTask 或线程池。
- 异常处理:网络请求可能会因为各种原因失败,如网络中断、服务器错误等,必须进行完善的异常处理。
- 数据解析:接收到的网络数据通常需要解析,常见的格式有 JSON、XML 等。可以使用 GSON、FastJSON 等库进行 JSON 数据解析。
- 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() { @Override public void onFailure(Call call, IOException e) { // 处理失败 mainHandler.sendEvent(InnerEvent.get(MSG_ERROR, \"请求失败: \" + e.getMessage())); } @Override public 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() { @Override public void onFailure(Call call, IOException e) { // 处理失败 mainHandler.sendEvent(InnerEvent.get(MSG_ERROR, \"请求失败: \" + e.getMessage())); } @Override public 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
谢谢阅读,烦请关注:
后续将持续更新!!