# 一步步搭建物联网系统(教你设计物联网系统)

# 1 Android简单示例

由于在某些嵌入式系统中使用的是Android系统，这里给出一个简单的Android App的示例，具体代码可以从clone自https://github.com/phodal/iot-android

代码说明，经过测试的版本有

- Android 2.3
- Android 4.0.4

机型有

- HTC G1 (android 2.3)
- Motor xt300 (android 2.3)
- Sony ST25I (android 4.0.4)
- MI2

应该可以在大部分的手机上工作。

## 1.1 调用Web Services GET

这里我们参考一篇文章来调用Web Services——Calling Web Services in Android using HttpClient

### 1.1.1 创建RESTClient

在这里我们首先会定义四个REST方法GET、POST、PUT、DELETE

    public void Execute(RequestMethod method) throws Exception {
        switch (method) {
        case GET: {
            // add parameters
            String combinedParams = "";
            if (!params.isEmpty()) {
                combinedParams += "?";
                for (NameValuePair p : params) {
                    String paramString = p.getName() + "="
                            + URLEncoder.encode(p.getValue(), HTTP.UTF_8);
                    if (combinedParams.length() > 1) {
                        combinedParams += "&" + paramString;
                    } else {
                        combinedParams += paramString;
                    }
                }
            }

            HttpGet request = new HttpGet(url + combinedParams);
            request.addHeader("Accept-Encoding", "gzip");

            // add headers
            for (NameValuePair h : headers) {
                request.addHeader(h.getName(), h.getValue());
            }

            executeRequest(request, url);
            break;
        }
        case POST: {
            HttpPost request = new HttpPost(url);
            request.addHeader("Accept-Encoding", "gzip");

            // add headers
            for (NameValuePair h : headers) {
                request.addHeader(h.getName(), h.getValue());
            }
            if (!data.equals("")) {
                request.setEntity(new StringEntity(data, HTTP.UTF_8));
            }

            if (!params.isEmpty()) {
                request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
            }

            executeRequest(request, url);
            break;
        }
        case PUT: {
            HttpPut request = new HttpPut(url);
            request.addHeader("Accept-Encoding", "gzip");

            // add headers
            for (NameValuePair h : headers) {
                request.addHeader(h.getName(), h.getValue());
            }
            if (!data.equals("")) {
                request.setEntity(new StringEntity(data, HTTP.UTF_8));
            }

            if (!params.isEmpty()) {
                request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
            }

            executeRequest(request, url);
            break;
        }
        case DELETE: {
            HttpDelete request = new HttpDelete(url);
            request.addHeader("Accept-Encoding", "gzip");

            // add headers
            for (NameValuePair h : headers) {
                request.addHeader(h.getName(), h.getValue());
            }

            executeRequest(request, url);
            break;
        }
        }
    }

这四个方法最后都执行executeRequest来获取响应结果。

    protected void executeRequest(HttpUriRequest request, String url) {

            HttpParams httpParameters = new BasicHttpParams();
            HttpConnectionParams.setConnectionTimeout(httpParameters,
                    timeoutConnection);
            HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

            HttpProtocolParams.setUseExpectContinue(httpParameters, false);
            request.setParams(httpParameters);

            setOauth(request);

            DefaultHttpClient client = new DefaultHttpClient();

            HttpResponse httpResponse;

            try {
                httpResponse = client.execute(request);
                responseCode = httpResponse.getStatusLine().getStatusCode();
                message = httpResponse.getStatusLine().getReasonPhrase();

                HttpEntity entity = httpResponse.getEntity();

                if (entity != null) {
                    InputStream instream = httpResponse.getEntity().getContent();
                    Header contentEncoding = httpResponse
                            .getFirstHeader("Content-Encoding");

                    if (contentEncoding != null
                            && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
                        instream = new GZIPInputStream(instream);
                    }

                    // instream = entity.getContent();
                    response = convertStreamToString(instream);

                    // Closing the input stream will trigger connection release
                    instream.close();
                }

            } catch (ClientProtocolException e) {
                client.getConnectionManager().shutdown();
                e.printStackTrace();
            } catch (IOException e) {
                client.getConnectionManager().shutdown();
                e.printStackTrace();
            }
        }

接着，我们便可以执行getResponse()函数来获取结果。

## 1.2 使用REST Client获取结果

使用RESTClient时，便可以用下面的示例

    RestClient client = new RestClient(tUrl);
    try {
        client.Execute(RequestMethod.GET);
        if (client.getResponseCode() != 200) {
            //do something
        }
        //JSONArray jArray = new JSONArray(client.getResponse());
    } catch (Exception e) {
        //do something
    }

而这时，我们只需要对相应的数据进行处理就可以了，如

    JSONArray jArray = new JSONArray(client.getResponse());
    JSONObject jObj=jArray.getJSONObject(0);
    vshow.setText(jObj.toString());

    outputJSON(jObj);

将他转换为String，接着在Android端上显示最后的结果。