?謝謝關注!!
前言:上一篇文章主要介紹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();}
}
三、網絡請求注意事項
- 線程管理: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() {@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
謝謝閱讀,煩請關注:
后續將持續更新!!