目录:
1、开启明文传输
2、权限申请
3、引入http插件
4、案例展示
5、《鸿蒙OS前端开发入门指南》文章合集
开启<span class="colour" style="color: rgb(224, 62, 45);">明文</span>传输 在<span class="colour" style="color: rgb(224, 62, 45);">config.json</span>配置文件添加如下配置(如果不开启可以不配置)
"deviceConfig": {
"default": {
"network": {
"usesCleartext": true
}
}
},
权限申请 在配置文件module中添加如下
"reqPermissions": [{
"name":"ohos.permission.INTERNET"
}],
引入zzr老师写的鸿蒙http插件
implementation 'com.zzrv5.zzrhttp:ZZRHttp:1.0.1'
案例1
使用方式,
new ImageNetWork(”当前的abilitySlice“,“创件的Image组建”,"图片地址").start();
网络图片类
package com.example.shangjinlieren.compontents;
import com.zzrv5.mylibrary.ZZRCallBack;
import com.zzrv5.mylibrary.ZZRHttp;
import com.zzrv5.mylibrary.ZZRResponse;
import ohos.aafwk.ability.AbilitySlice;
import ohos.agp.components.Image;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;
public class ImageNetWork {
private final static HiLogLabel LABEL_LOG = new HiLogLabel(HiLog.LOG_APP, 0, "HmOSImageLoader");
private AbilitySlice abilitySlice;
private Image image;
private String url;
public ImageNetWork(AbilitySlice abilitySlice, Image image, String url) {
this.abilitySlice = abilitySlice;
this.image = image;
this.url = url;
}
public void start() {
ZZRHttp.get(url, new ZZRCallBack.CallBackString() {
@Override
public void onFailure(int code, String errorMessage) {
//http访问出错了,此部分内容在主线程中工作;
//可以更新UI等操作,请不要执行阻塞操作。
System.out.println("errorMessage"+errorMessage);
}
@Override
public String onParseResponse(ZZRResponse response) {
//创建图片源
ImageSource imageSource = ImageSource.create(response.inputStream, null);
//根据图片源创建位图
PixelMap pixelMap = imageSource.createPixelmap(null);
//需要异步渲染UI
abilitySlice.getUITaskDispatcher().asyncDispatch(new Runnable() {
@Override
public void run() {
//展示到组件上
System.out.println("挂载了");
image.setPixelMap(pixelMap);
pixelMap.release();
}
});
return super.onParseResponse(response);
}
@Override
public void onResponse(String response) {
}
});
}
}
作者:BLUESKYHOST
想了解更多内容,请访问51CTO和华为合作共建的鸿蒙社区:https://harmonyos.51cto.com/