https://harmonyos.51cto.com/#zz
1. AsyncHttpHarmony功能介绍
1.1. 组件介绍
在做HarmonyOS开发过程中,用java原生的HttpsURLConnection实现网络请求很难高效的达到预期效果。我们需要高效的处理数据解析,更加快捷的实现UI线程更新,这里基于方网络框架AsyncHttpClient二次封装,更加高效实现网络请求及数据处理。同时HarmonyOS为我们提供了TaskDispatcher类派发同步任务,达到更新UI的效果。
1.2. TV模拟器上运行效果
请求前:
点击get请求之后:
2. AsyncHttpHarmony使用方法
2.1. 为应用添加httplibrary-debug.har包依赖
在应用模块中调用HAR,常用的添加依赖的方式包括如下两种。
Ø 方式一:依赖本地HAR
第一步:将httplibrary-debug.har复制到entry\libs目录下即可(由于build.gradle中已经依赖libs目录下的*.har,因此不需要再做修改)。
查看工程目录中build.gradle下的*.har是否存在:
第二步:需要添加外部依赖实现Header类的引入,引入方式如下图,引入完之后同步下即可可以使用。
2.2. 为应用添加网络权限,config.json文件部分代码如下:
- "reqPermissions": [
- {
- "name": "ohos.permission.INTERNET",
- "reason": "",
- "usedScene": {
- "ability": [
- "com.example.ohosdemo.MainAbility",
- "com.example.ohosdemo.slice.MainAbilitySlice"
- ],
- "when": "always"
- }
- },
以上操作无误之后就可以进行编码了!
3. AsyncHttpHarmony开发实现
3.1. 主页面的布局文件
定义一个Text文本用来显示请求返回的数据,一个text实现请求点击事件
- <?xml version="1.0" encoding="utf-8"?>
- <DirectionalLayout
- xmlns:ohos="http://schemas.huawei.com/res/ohos"
- ohos:height="match_parent"
- ohos:width="match_parent"
- ohos:orientation="vertical">
- <Text
- ohos:id="$+id:tvResult"
- ohos:height="match_content"
- ohos:width="match_content"
- ohos:background_element="$graphic:background_ability_main"
- ohos:layout_alignment="horizontal_center"
- ohos:text="数据显示"
- ohos:text_size="50"
- ohos:top_margin="180vp"
- />
- <Text
- ohos:id="$+id:tvRequest"
- ohos:height="match_content"
- ohos:width="match_content"
- ohos:background_element="$graphic:background_ability_main"
- ohos:layout_alignment="horizontal_center"
- ohos:text="get请求"
- ohos:text_size="50"
- ohos:top_margin="80vp"
- />
- </DirectionalLayout>
3.2. MainAbilitySlice代码如下
核心代码是initListener,其中声明了一个 AsyncHttpClient对象,设置请求参数,调用get方法获取ulr返回结果,然后通过TaskDispatcher类派发同步任务达到更新UI的效果,代码如下:
- package com.huawei.asynchttpharmonyos.slice;
- import com.example.httplibrary.utils.AsyncHttpClient;
- import com.example.httplibrary.utils.JsonHttpResponseHandler;
- import com.example.httplibrary.utils.RequestParams;
- import com.huawei.asynchttpharmonyos.ResourceTable;
- import cz.msebera.android.httpclient.Header;
- import ohos.aafwk.ability.AbilitySlice;
- import ohos.aafwk.content.Intent;
- import ohos.agp.components.Component;
- import ohos.agp.components.Text;
- import ohos.hiviewdfx.HiLog;
- import ohos.hiviewdfx.HiLogLabel;
- public class MainAbilitySlice extends AbilitySlice {
- private Text tvRequest,tvResult;
- private static final String TAG = "MainAbilitySlice";
- private static final HiLogLabel label=new HiLogLabel(HiLog.DEBUG,0x00100,"async-http");
- @Override
- public void onStart(Intent intent) {
- super.onStart(intent);
- super.setUIContent(ResourceTable.Layout_ability_main);
- initView();
- initListener();
- }
- private void initView() {
- tvResult = (Text) findComponentById(ResourceTable.Id_tvResult);
- tvRequest = (Text) findComponentById(ResourceTable.Id_tvRequest);
- }
- private void initListener() {
- tvRequest.setClickedListener(new Component.ClickedListener() {
- @Override
- public void onClick(Component component) {
- String url="https://apis.juhe.cn/simpleWeather/query";
- String key="32becf485f7f174d4385957b62f28f61";
- //这里获取AsyncHttpClient实例, 这个类提供了get post delete put 请求对外的接口方法
- AsyncHttpClient client=new AsyncHttpClient();
- //这里是我们包装参数的实体类
- RequestParams params=new RequestParams();
- params.put("city","西安");
- params.put("key",key);
- /这里是实现get请求的方,JsonHttpResponseHandler会重写请求成功的onSuccess和onFailure两个方法,两个方法内部做具体业务逻辑
- client.get(url,params, new JsonHttpResponseHandler() {
- @Override
- public void onSuccess(int statusCode, Header[] headers, String responseString) {
- super.onSuccess(statusCode, headers, responseString);
- HiLog.error(label,"zel-onSuccess:"+responseString,responseString);
- // 通知主线程更新UI
- getUITaskDispatcher().asyncDispatch(new Runnable() {
- @Override
- public void run() {
- // 这里具体业务Text文本显示请求数据
- tvResult.setText(responseString);
- }
- });
- }
- @Override
- public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
- super.onFailure(statusCode, headers, responseString, throwable);
- HiLog.error(label,"zel-onFailure:"+responseString,responseString);
- }
- });
- }
- });
- }
- @Override
- public void onActive() {
- super.onActive();
- }
- @Override
- public void onForeground(Intent intent) {
- super.onForeground(intent);
- }
- }
项目源代码地址:https://github.com/isoftstone-dev/Http-Async-HarmonyOS
©著作权归作者和HarmonyOS技术社区共同所有,如需转载,请注明出处,否则将追究法律责任
https://harmonyos.51cto.com/#zz