参考资料
在鸿蒙(HarmonyOS)环境下,优雅的完成Http访问网络【教程】
api讲解
创建 url
URL url=new URL(urlstr);//todo 创建 url
得到HttpURLConnection对象
HttpURLConnection httpURLConnection= (HttpURLConnection) url.openConnection();
设置请求方式
httpURLConnection.setRequestMethod(“GET”);
建立连接
httpURLConnection.connect()
得到请求状态码
int code=httpURLConnection.getResponseCode()
代码如下
try {
String urlstr="https://www.baidu.com/";
URL url=new URL(urlstr);//todo 创建 url
//todo 得到HttpURLConnection对象
HttpURLConnection httpURLConnection= (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("GET");//todo 设置请求方式
httpURLConnection.connect();//todo 建立连接
int code=httpURLConnection.getResponseCode();//todo 获取请求状态码
if(code==HttpURLConnection.HTTP_OK){
//todo 请求成功 处理相关业务
}else{
//todo 失败业务处理
}
}catch (Exception e){
e.printstacktrace();
}
代码运行
config.json添加权限
"reqPermissions": [{"name":"ohos.permission.INTERNET"}],
设置访问模式
"deviceConfig": {
"default": {
"network": {
"cleartextTraffic": true
}
}
},
xml布局绘制(在xml 布局设置两个text按钮,一个用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:text_helloworld"
ohos:height="match_content"
ohos:width="match_parent"
ohos:text_alignment="center"
ohos:background_element="#ed6162"
ohos:layout_alignment="horizontal_center"
ohos:text="网络请求"
ohos:text_size="40vp"
/>
<Text
ohos:id="$+id:TextResult"
ohos:height="match_parent"
ohos:width="match_parent"
ohos:text_alignment="top|left"
ohos:text="结果"
ohos:multiple_lines="true"
ohos:text_size="20vp"
/>
</DirectionalLayout>
java代码实现(分为三个方法 第一个方法实现点击事件 ,第二个方法实现网络请求的事件,第三个方法输入流转化为字符串的功能,最后子线程切换到ui主线程,显示字符串)代码如下
package com.harmony.alliance.myapplication.slice;
import com.harmony.alliance.myapplication.ResourceTable;
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;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class MainAbilitySlice extends AbilitySlice {
static final HiLogLabel LABEL = new HiLogLabel(HiLog.LOG_APP, 0x00201, "MY_TAG");
Text textResult;
@Override
public void onStart(Intent intent) {
super.onStart(intent);
super.setUIContent(ResourceTable.Layout_ability_main);
//todo 用于显示结果的按钮
textResult=findComponentById(ResourceTable.Id_TextResult);
//todo 实现点击事件
findComponentById(ResourceTable.Id_text_helloworld).setClickedListener(new Component.ClickedListener() {
@Override
public void onClick(Component component) {
//todo 开启线程
new Thread(){
@Override
public void run() {
super.run();
networkGet();
}
}.start();
}
});
}
/**
* 发起网络请求
*/
public void networkGet(){
try {
String urlstr="https://www.baidu.com/";
URL url=new URL(urlstr);//todo 创建 url
//todo 得到HttpURLConnection对象
HttpURLConnection httpURLConnection= (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("GET");//todo 设置请求方式
httpURLConnection.connect();//todo 建立连接
int code=httpURLConnection.getResponseCode();//todo 获取请求状态码
if(code==HttpURLConnection.HTTP_OK){
InputStream inputStream=httpURLConnection.getInputStream();//todo 获取网络得到输入流
byte[] data = read(inputStream);//todo 转化为字节
String html = new String(data, "UTF-8");// todo 字节转化为字符串
HiLog.error(LABEL,html);
//todo 从子线程切换到Ui 主线程
getUITaskdispatcher().syncdispatch(() -> {
textResult.setText(html);//todo 显示结果
});
}
}catch (Exception e){
e.printstacktrace();
}
}
/**
* 输入流转化为字节
* @param inStream 输入流
* @return 返回字节
* @throws Exception 抛出的异常
*/
public static byte[] read(InputStream inStream) throws Exception{
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while((len = inStream.read(buffer)) != -1)
{
outStream.write(buffer,0,len);
}
inStream.close();
return outStream.toByteArray();
}
}
运行效果
欲了解更多更全技术文章,欢迎访问https://developer.huawei.com/consumer/cn/forum/?ha_source=zzh
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。