APP与服务器之间通过 http(POST、GET)进行数据交互 ( 实现一个简单的物联网系统-1 )

一、APP POST 数据到服务器

  首先 post 的数据应该包括识别这个花卉的信息和我们想要浇水的量,这里我们识别花卉采用花卉的名字,这样后台程序通过花卉名来对应更新数据库中该花的浇水量。

  1. mFlower_name:花卉名
  2. mBulk : 浇水量

实现代码如下:
注意:

  1. String urlPath 中的 IP 地址是我局域网的地址,如果你的后台程序是在云服务器上运行的那么应改成云服务器的公网IP。不过可以先在局域网内实现嘛。
  2. http 的默认端口号为80,但由于我用的是springboot框架打包成的jar包,自带了嵌入的tomcat,而tomcat容器默认的端口号为8080(可以在配置文件(.yml)中更改)。
  3. 服务端的代码可参照专栏中的下一篇文章。
      Code:
/*-- 将浇水量等信息上传到服务器    安卓4.0以后必须在子线程中执行 --*/
new Thread() {
    @Override
    public void run() {
        try {
            String urlPath = "http://192.168.43.148:8080/appPost";  	//URL
            URL url = new URL(urlPath);
            HttpURLConnection coon = (HttpURLConnection) url.openConnection();
            coon.setRequestMethod("POST");	//请求方式为POST
            coon.setConnectTimeout(5000);
            coon.setRequestProperty("Content-Type", "application/json");     //设置发送的数据为 json 类型,会被添加到http body当中
            String json = "{\"name\":\""+ mFlower_name+"\"," + "\"bulk\":" + "\"" +mBulk+ "\"}";    //将要发送的花卉数据字符串连接成json格式
            coon.setRequestProperty("Content-Length", String.valueOf(json.length()));

            //post请求把数据以流的方式写给服务器,指定请求的输出模式
            coon.setDoOutput(true);
            coon.getOutputStream().write(json.getBytes());

            int code = coon.getResponseCode();
            if (code == 200) {
                System.out.println("请求成功");
            } else {
                System.out.println("请求失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("请求失败");
        }
    }
}.start();

二、APP 从服务器 GET 数据

  APP 同样需要从服务器获得花卉的状态信息来更新显示界面,如更新到最新的土壤湿度、光照强度等显示给用户。
实现代码如下:
注意:

  1. 从服务器得到的数据为 list 形式,所以解析较复杂一些,这取决于你服务器返回什么样的数据,在下一篇文章会有说明。服务器直接返回 map 形式APP这边会更好解析。具体百度啦!
    Code:
new Thread() {
    @Override
    public void run() {
        //查询服务器 得到花卉的信息  更新显示的数据
        try {
            String urlPath = "http://192.168.43.148:8080/appQuery?flower_name=" + mFlower_name;
            URL url = new URL(urlPath);
            HttpURLConnection coon = (HttpURLConnection) url.openConnection();
            coon.setRequestMethod("GET");
            coon.setConnectTimeout(5000);

            int code = coon.getResponseCode();
            if (code == 200) {
                //1.得到输入流
                InputStream is = coon.getInputStream();
                //2.将流用自己写的StreamUtils转化为字符串  改字符串为json格式
                String flowerInfo = StreamUtils.readStream(is);
                //3.解析json数据(这里是list形式)  并显示数据
                JSONArray flowerJsonArray = new JSONArray(flowerInfo);
                // 这里的数组长度其实是1
                for (int i = 0; i < flowerJsonArray.length(); i++) {
                    JSONObject flowerJsonObject = flowerJsonArray.getJSONObject(i);
                    mTv_temperature.setText(flowerJsonObject.getString("temperature"));//温度
                    mTv_humidity.setText(flowerJsonObject.getString("humidity"));//湿度
                    mTv_co2.setText(flowerJsonObject.getString("co2"));//CO2 浓度
                }
            } else {
                Message msg = Message.obtain();
                msg.what = STATUS_ERROR;
                mHandler.sendMessage(msg);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}.start();

三、APP 界面部分

  这部分就主要看自己如何去设计了,主要还是要多学习一些,才能做出更好看、功能更加丰富的APP。下面展示一下我做的APP(由于技术原因以及没有艺术细胞,做的着实有些丑)。

四、相关疑问

  1. 后台相关的代码呢?
    在下一节贴上我的服务端的代码,其实站在SpringBoot的肩膀上,我们后台的搭建显得异常的容易。
  2. APP 的其他代码和功能呢?
    这里我之列出了POST 和 GET 过程相关的代码,如果真的要实现众多功能,还是要花好长一段时间去学习安卓。

五、学习方法

  1. 我个人是通过学习完Java以后,在某宝花了几十块钱买的教学视频,还有哔哩哔哩上的天哥在奔跑的视频也还不错,等等。这里仅仅只是个人的学习过程,仅供参考。

六、专栏地址

  https://blog.csdn.net/CSDN_X_W/column/info/33567

  • 11
    点赞
  • 83
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
好的,下面是一个使用 ng-alain 框架和服务器进行交互的示例: 1. 在你的 Angular 项目中安装 ng-alain 框架: ``` ng add ng-alain ``` 2. 创建一个服务来进行服务器交互。在你的项目中创建一个名为 `example.service.ts` 的文件,并使用以下代码: ``` import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Injectable({ providedIn: 'root', }) export class ExampleService { private apiUrl = 'http://example.com/api'; constructor(private http: HttpClient) {} public getExampleData() { return this.http.get(`${this.apiUrl}/example`); } public postExampleData(data: any) { return this.http.post(`${this.apiUrl}/example`, data); } } ``` 3. 在你的组件中使用服务来与服务器进行交互。在你的项目中创建一个名为 `example.component.ts` 的文件,并使用以下代码: ``` import { Component, OnInit } from '@angular/core'; import { ExampleService } from './example.service'; @Component({ selector: 'app-example', templateUrl: './example.component.html', styleUrls: ['./example.component.less'], }) export class ExampleComponent implements OnInit { public exampleData: any; constructor(private exampleService: ExampleService) {} ngOnInit() { this.exampleService.getExampleData().subscribe((data) => { this.exampleData = data; }); } public onSubmit(data: any) { this.exampleService.postExampleData(data).subscribe(() => { console.log('Data submitted successfully'); }); } } ``` 在这个例子中,我们创建了一个名为 `ExampleService` 的服务来与服务器进行交互。在组件中,我们注入了这个服务,并在 `ngOnInit` 中调用了 `getExampleData()` 方法来获取例子数据,并将其存储在 `exampleData` 变量中。我们还创建了一个名为 `onSubmit` 的方法来提交数据服务器,它使用了 `postExampleData()` 方法来提交数据,并在提交成功后打印一条消息。 希望这个例子可以帮助你了解如何使用 ng-alain 框架与服务器进行交互
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值