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

运城做网站要多少钱大一html网页制作作业

运城做网站要多少钱,大一html网页制作作业,asp网站gzip压缩,网站颜色正确搭配实例谢谢关注!! 前言:上一篇文章主要介绍HarmonyOs开发之———Video组件的使用:HarmonyOs开发之———Video组件的使用_华为 video标签查看-CSDN博客 HarmonyOS 网络开发入门:使用 HTTP 访问网络资源 HarmonyOS 作为新一代智能终端…

 谢谢关注!!

前言:上一篇文章主要介绍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.dtcms.com/wzjs/191206.html

相关文章:

  • 做网站资源存储百度关键词刷排名教程
  • 做视频网站服务器要求谷歌搜索引擎网页版入口
  • 济宁网站建设兼职网站营销网站营销推广
  • tp5网站文档归档怎么做2021小说排行榜百度风云榜
  • 济南网站建设的费用网络营销的原理
  • 网站建设在学校中的作用北京网站建设专业公司
  • 做中澳原产地证的网站长春网站优化团队
  • 北京国税局网站做票种核定长沙关键词优化公司电话
  • 怎样在淘宝网做网站销售找客户的方法
  • 代理小企业网站建设淘宝数据查询
  • 小公司建网站 优帮云seo整站优化
  • .net网站开发岗位百度seo在线优化
  • ECS 安装wordpressseo优化一般包括哪些
  • 网站验证码是如何做的网站做seo教程
  • 海口网站建设fwlitapp推广引流
  • 保健品手机网站模板泉州关键词排名工具
  • 安仁网站制作镇江网站建设方案
  • 电子商务平台网站模板百度广告上的商家可靠吗
  • 有那些专门做财务分析的网站下载百度软件
  • 网站建设会使用的技术公众号推广方法
  • 科技公司网站源码如何做一个网站的seo
  • 成都网站制作工作室百度网讯科技客服人工电话
  • 网站开发商城app东莞seo外包公司
  • 网站搜索排名优化怎么做seo在线培训机构
  • 电商网站建设需要多少钱seo流量排名软件
  • 山东日照今天的疫情是啥情况无锡百度快照优化排名
  • 个性网站制作网店培训骗局
  • 网站开发的软件环境有哪些西安百度推广竞价托管
  • 网站设计服务流程论坛企业推广
  • php做网站用框架免费顶级域名注册网站