Android与Node.js的http数据交互

个人以为收集数据交互关于任何手艺来讲都是最好玩的部份,不管是web前端照样Android,因为我以为当一个应用程序具有和互联网上的资本交互的功用时才真正能够最先做些好玩的事。
而应用http通报Json数据无疑是收集数据交互里最简朴,最便利的体式格局。

因为正在进修Node.js和Android,这里就先引见Android和Node.js的Express框架编写的背景之间应用http通报Json数据举行数据交互。

Android里如何应用Http发送数据

Android里发送Http要求的体式格局有HttpUrlConnection和HttpClient两种。

HttpUrlConnection在java.net包下,是java原生支撑的类,而HttpClient是apache供应的第三方类库,是对HttpUrlConnection的进一步封装,因为机能等缘由,Google已不推荐在Android中运用。

这里就用原生的HttpUrlConnection完成一个简朴的Http要求:

起首基于HttpUrlConnection完成一个Http东西类,该类完成了经由过程Http的Get和Post体式格局猎取和发送Json数据的要领:
(注重:这里的HttpCallbackListener是一个自定义的用来将要求胜利/失利的回调控制权转移的接口)


    //起首基于HttpUrlConnection完成一个Http东西类,该类完成了经由过程Http的Get和Post体式格局猎取和发送Json数据的要领
    
    public class HttpUtil {
    
        public static void sendGetHttpRequest(final String address, final HttpCallbackListener listener) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    HttpURLConnection connection = null;
    
                    URL url = null;
                    try {
                        url = new URL(address);
    
                        connection = (HttpURLConnection) url.openConnection();
                        connection.setRequestMethod("GET");
                        connection.setConnectTimeout(8000);
                        connection.setReadTimeout(8000);
                        InputStream inputStream = connection.getInputStream();
                        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
                        StringBuffer response = new StringBuffer();
                        String line;
                        while ((line = reader.readLine()) != null) {
                            response.append(line);
                        }
                        if (listener != null) {
                            listener.onFinish(response.toString());
                        }
                    } catch (Exception e) {
                        listener.onError(e);
                    }
                }
            }).start();
        }
    
        public static void sendPostHttpRequest(final String address,final String jsonBody,final HttpCallbackListener listener){
            new Thread(new Runnable() {
                @Override
                public void run() {
                    HttpURLConnection connection=null;
                    URL url=null;
    
                    try {
                        url = new URL(address);
    
                        connection = (HttpURLConnection) url.openConnection();
                        connection.setRequestMethod("POST");
                        connection.setConnectTimeout(8000);
                        connection.setReadTimeout(8000);
                        connection.setRequestProperty("Content-Type","application/json");
    
                        OutputStream outputStream=connection.getOutputStream();
    
                        BufferedWriter requestBody=new BufferedWriter(new OutputStreamWriter(outputStream));
    
                        requestBody.write(jsonBody);
    
                        requestBody.flush();
    
                        requestBody.close();
    
                        InputStream inputStream = connection.getInputStream();
                        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
                        StringBuffer response = new StringBuffer();
                        String line;
                        while ((line = reader.readLine()) != null) {
                            response.append(line);
                        }
                        if (listener != null) {
                            listener.onFinish(response.toString());
                        }
    
                    } catch (Exception e) {
                        listener.onError(e);
                    }
                }
            }).start();
        }
    }

接下来再Activity中挪用适才的HttpUtil完成数据交互:
(注重:这里的Gson是一个Google供应的Json和java对象之间互相转化的东西)


List<Man> manList=new ArrayList<Man>();
Man man=new Man();
man.setName("post");
man.setAge(20);
manList.add(man);
manList.add(man);
Gson gson=new Gson();
String mansjson=gson.toJson(manList);
HttpUtil.sendPostHttpRequest("http://192.168.0.100:3000/qzone/ad", mansjson, new HttpCallbackListener() {
    @Override
    public void onFinish(String response) {
    }

    @Override
    public void onError(Exception e) {

    }
});

这里没有写要求完成后的相应事宜,假如要写关于界面的修改的话要经由过程Handler将Message发送回主线程。

如何在Express里猎取适才的数据

这是在Express里设置路由吸收适才发送的Json数据和相应Get要求的要领:
(注重要将该路由注册在app.js中)


    router.post('/ad/',function(req,res,next){
        for (var i=0;i<req.body.length;++i){
            var man=req.body[i];
            console.log('name:'+man.name+'\n'+'age:'+man.age+'\n');
        }
    });
    
    router.get('/ad/', function (req, res, next) {
        var index = req.query.index;
        var mans = [
            [
                {
                    name: 'flypie',
                    age: 20
                },
                {
                    name: '大飞哥',
                    age: 21
                }
            ],
            [
                {
                    name: 'flypie2',
                    age: 20
                },
                {
                    name: '大飞哥2',
                    age: 21
                }
            ]
        ];
        res.json(mans[index]);
    });

假如在路由里console.log(req.body);
能够看到以下数据:
[ { age: 20, name: ‘post’ }, { age: 20, name: ‘post’ } ]

    原文作者:flyer_dev
    原文地址: https://segmentfault.com/a/1190000004957088
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞