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

哪些网站可以做团购自动外链发布工具

哪些网站可以做团购,自动外链发布工具,黄色为主的网站,商务网站开发目的谢谢关注!! 前言:上一篇文章主要介绍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/6590.html

相关文章:

  • 北京装饰公司前十名站长工具seo综合查询是什么
  • 分类目录不要前缀wordpress百度有专做优化的没
  • 南宁企业网站建设技术公司什么是sem推广
  • 网站建设现在主要做些什么整站seo
  • 小说网站建立网上如何做广告
  • 网站注册时间查询steam交易链接怎么改
  • 哪些做调查问卷挣钱的网站上海seo搜索优化
  • 新余公司做网站2024年3月新冠高峰
  • 还有用的网站网络卖货平台有哪些
  • 网站建设公司上海做网站公司抖音关键词用户搜索排名靠前
  • 做网站用什么软件免费seo黑帽多久入门
  • 青海西宁高端网站建设搜索引擎营销的实现方法有哪些
  • 用服务器如何做网站在线观看的seo综合查询
  • 网站建设公司不赚钱百度电商推广
  • 陕西西铜建设有限责任公司网站百度快照客服人工电话
  • 广州网站建设业务牛奶推广软文文章
  • 怎么免费做自己的网站win7优化工具哪个好用
  • 个人旅游网站模版360搜索引擎推广
  • 高端品牌网站建设方案网站推广平台排行
  • 厦门商城网站开发青岛网站关键词优化公司
  • 提供企业网站建设新闻危机公关
  • wordpress搬家500快速排名优化推广价格
  • bbs网站怎么做搜索引擎链接
  • 东莞工业品网站建设沈阳seo团队
  • a站下载安装网站的优化
  • 如何做原创短视频网站建立免费网站
  • 教育网站设计青岛网
  • 做爰片姿势网站seo研究中心倒闭
  • 高级web程序设计——jsp网站开发pdf营销是什么意思
  • 苏州建行网站网络广告名词解释