19 Android簡單示例

2018-02-24 15:53 更新

Andriod簡單示例

由于在某些嵌入式系統(tǒng)中使用的是Android系統(tǒng),這里給出一個簡單的Android App的示例,具體代碼可以從clone自https://github.com/phodal/iot-android

代碼說明,經(jīng)過測試的版本有

  • Android 2.3
  • Android 4.0.4

機型有

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

應該可以在大部分的手機上工作。

調(diào)用Web Services GET

這里我們參考一篇文章來調(diào)用Web Services——Calling Web Services in Android using HttpClient

創(chuàng)建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;
    }
    }
}

這四個方法最后都執(zhí)行executeRequest來獲取響應結(jié)果。

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();
        }
    }

接著,我們便可以執(zhí)行g(shù)etResponse()函數(shù)來獲取結(jié)果。

使用REST Client獲取結(jié)果

使用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
}

而這時,我們只需要對相應的數(shù)據(jù)進行處理就可以了,如

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

outputJSON(jObj);

將他轉(zhuǎn)換為String,接著在Android端上顯示最后的結(jié)果。

以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號