[Android]HttpPost之post请求传递Json数据

懒得打字

/**
     * 发送post请求传递Json
     */
    public void jieXi() {

        new Thread(new Runnable() {

            public void run() {
                // Json中的引号必须加 \ 转义
                String getLightJson = "{\"object\":\"light\",\"action\":\"get\"}";
                String jsonParent = getJsonParent(getLightJson);
                if (ifJsonParentOk(jsonParent)) {
                    ArrayList<light> query = getQuery(jsonParent);
                    for (light l : query) {
                        System.out.println("----------");
                        System.out.println("co2-->" + l.getCo2());
                        System.out.println("pm2.5-->" + l.getPm2_5());
                        System.out.println("----------");
                    }
                }
            }
        }).start();
    }

    /**
     * 返回Json
     * 
     * @param json
     * @return
     */
    public String getJsonParent(String json) {
        try {
            URI uri = new URI(urlString);
            HttpPost mhttpPost = new HttpPost(uri);
            // 设置请求头
            mhttpPost.setHeader("Accept", "application/json");
            mhttpPost.setHeader("Content-Type", "application/json");
            // Json数据在这里
            HttpEntity mEntity = new StringEntity(json, HTTP.UTF_8);
            mhttpPost.setEntity(mEntity);
            // 发送请求
            HttpResponse response = new DefaultHttpClient().execute(mhttpPost);
            String str = EntityUtils.toString(response.getEntity());
            System.out.println("--->" + str);
            return str;
        } catch (Exception e) {

        }
        return "";
    }

    /**
     * 返回码是不是ok
     * 
     * @param str
     * @return
     */
    public boolean ifJsonParentOk(String str) {
        try {
            jsonObject = new JSONObject(str);
            String result = jsonObject.getString("result");
            if (result.equals("ok")) {
                return true;
            }
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 解析返回的json
     * 
     * @param str
     * @return
     */
    public ArrayList<light> getQuery(String str) {
        ArrayList<light> arrayList = new ArrayList<light>();
        try {
            light _light = new light();
            jsonObject = new JSONObject(str);
            _light.setPm2_5(jsonObject.getString("pm2.5"));
            _light.setCo2(jsonObject.getString("co2"));
            arrayList.add(_light);
            return arrayList;
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }

 

posted @ 2015-04-15 17:37  小菜希  阅读(4023)  评论(0编辑  收藏  举报