> 文档中心 > Deveco studio 鸿蒙app访问网络详细过程(js)

Deveco studio 鸿蒙app访问网络详细过程(js)


效果图

话不多说,上效果:

 

 

安装IDE工具Deveco studio

下载地址:HUAWEI DevEco Studio和SDK下载和升级 | HarmonyOS开发者

双击exe文件开始安装,详细步骤看官方文档。

我使用的版本是3.0.0.991

 创建项目

选择Empty Ability,点击next

项目结构如下:

 

项目配置

鸿蒙3.0访问网络默认支持https协议 

所以我们需要要到配置文件config.json中进行配置

在"deviceConfig": {}中加入以下内容,

"default": {  "network": {"cleartextTraffic": true}}cleartextTraffic 表示是否允许应用使用明文网络流量(例如,明文HTTP)

app访问网络需要申请相关权限:ohos.permission.INTERNET

 

 到此项目配置结束了。

功能开发

js代码

data: {    title1: "",    title2: "",},//启动该页面时,会执行该方法
getHttp:function(){    let httpRequest =http.createHttp();    httpRequest.on('headerReceive',(header)=>{console.info('header:'+JSON.stringify(header));    });    httpRequest.request( "http://ip:8888/wx_test",   //这里是你要访问的地址 {     method:http.RequestMethod.GET,//默认get方法     connectTimeout:60000,     readTimeout:60000, },(err,data)=>{ if(!err){     this.title1=data.result;     //将返回的结果赋值给title变量 // data.result为http响应内容,可根据业务需要进行解析     console.info('Result:'+data.result);     console.info('code:'+data.cookies);    // data.header为http响应头,可根据业务需要进行解析     console.info('header:' + JSON.stringify(data.header));     console.info('cookies:' + data.cookies); // 8+ } else{     console.info('errorhh:' + JSON.stringify(err));  // 当该请求使用完毕时,调用destroy方法主动销毁。     httpRequest.destroy(); }    }    )},

hml代码

{{ title1 }}

css代码

.container {    height: 100%;    width: 100%;    align-items:center;    align-content: center;    flex-direction: column;}.title {    font-size: 60px;    text-align: center;    justify-content: center;    text-color: red;    width: 100%;    height: 40%;    margin: 10px;    background-color: antiquewhite;}.button_div{    width: 100%;    height: 40%;    background-color: bisque;    display: flex;/**垂直居中**/    align-items: center;/**水平居中**/    justify-content: center;}.buttonViews{    width: 80%;    height: 40%;    border: 5px solid blue ;    margin: 6px;    border-radius: 10px;    display: flex;    align-items: center;    justify-content: center;}.input{    font-size: 20px;    background-color: aqua;    display:flex;}.image{    width: 100%;    height: 400px;}@media screen and (orientation: landscape) {    .title { font-size: 60px;    }}@media screen and (device-type: tablet) and (orientation: landscape) {    .title { font-size: 100px;    }}

前沿知识,制作不易,开心给点

 

 

至此结束,祝大家好运!