Android通過HttpURLConnection擷取JSON並進行UI更新

來源:互聯網
上載者:User

標籤:thread   android   json   

本例子中使用的是:HttpURLConnection+Thread+Handler的組合,在 new Thread中通過HttpURLConnection擷取JSON資料後並在Handler裡對UI介面進行更新。






也可以用過HttpClient ,AsyncTask實現此功能,此處就不說啦。


廢話不多少直接上代碼了






-------------------------------分割線----------------------------------------


activity_main.xml(只有一個簡單TextView,用於展示擷取JSON後更新其Text)




<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"      xmlns:tools="http://schemas.android.com/tools"      android:id="@+id/container"      android:layout_width="match_parent"      android:layout_height="match_parent"      tools:context="com.zb.json_text.MainActivity"      tools:ignore="MergeRootFrame"      android:background="#f1f1f1"      android:orientation="vertical" >        <TextView           android:id="@+id/textview_01"          android:layout_width="match_parent"          android:layout_height="wrap_content"          android:text="出發吧,總會到達..."/>           </LinearLayout> 

 


MainActivity.java




package com.zb.json_text;    import java.io.ByteArrayOutputStream;  import java.io.InputStream;  import java.net.HttpURLConnection;  import java.net.URL;  import java.util.ArrayList;  import java.util.HashMap;  import java.util.List;  import java.util.Map;      import org.json.JSONArray;  import org.json.JSONObject;    import android.app.Activity;  import android.os.Bundle;  import android.os.Handler;  import android.widget.TextView;    public class MainActivity extends Activity {        private TextView textview_01;      private List<Map<String, String>> slist;        private Handler handler = new Handler() {          public void handleMessage(android.os.Message msg) {              switch (msg.what) {              case 0:                  Map<String, String> map = slist.get(2); // 例子而已,直接擷取下標為2的值了,可以通過迴圈將list的值取出                  textview_01.setText(map.get("title"));//在handler中更新UI                  break;                default:                  break;              }          }      };        @Override      protected void onCreate(Bundle savedInstanceState) {          super.onCreate(savedInstanceState);          setContentView(R.layout.activity_main);            final String path = "http://m.lalas.cn/help/all_1.html?format=json&size=5";          textview_01 = (TextView) findViewById(R.id.textview_01);            new Thread() {//建立子線程進行網路訪問的操作              public void run() {                  try {                      slist = getJSONObject(path);                      handler.sendEmptyMessage(0);                  } catch (Exception e) {                      e.printStackTrace();                  }              }          }.start();      }        /**       * 擷取網路中的JSON資料       * @param path       * @return       * @throws Exception       */      public static List<Map<String, String>> getJSONObject(String path)              throws Exception {            List<Map<String, String>> list = new ArrayList<Map<String, String>>();          Map<String, String> map = null;          URL url = new URL(path);          // 利用HttpURLConnection對象,我們可以從網頁中擷取網頁資料          HttpURLConnection conn = (HttpURLConnection) url.openConnection();          // 單位為毫秒,設定逾時時間為5秒          conn.setConnectTimeout(15 * 1000);          // HttpURLConnection對象是通過HTTP協議請求path路徑的,所以需要佈建要求方式,可以不設定,因為預設為get          conn.setRequestMethod("GET");          if (conn.getResponseCode() == 200) {// 判斷請求碼是否200,否則為失敗              InputStream is = conn.getInputStream(); // 擷取輸入資料流              byte[] data = readStream(is); // 把輸入資料流轉換成字串組              String json = new String(data); // 把字串群組轉換成字串                // 資料形式:{"total":2,"success":true,"arrayData":[{"id":1,"name":"張三"},{"id":2,"name":"李斯"}]}              JSONObject jsonObject = new JSONObject(json); // 返回的資料形式是一個Object類型,所以可以直接轉換成一個Object              int total = jsonObject.getInt("count");              String keywords = jsonObject.getString("keywords");                // 裡面有一個數組資料,可以用getJSONArray擷取數組              JSONArray jsonArray = jsonObject.getJSONArray("data");              for (int i = 1; i < jsonArray.length(); i++) {                  JSONObject item = jsonArray.getJSONObject(i); // 得到每個對象                  int id = item.getInt("id");                  String title = item.getString("title");                  String description = item.getString("description");                  int time = item.getInt("time");                  map = new HashMap<String, String>();                  map.put("id", id + "");                  map.put("title", title);                  map.put("description", description);                  map.put("time", time + "");                  list.add(map);              }          }            return list;      }        private static byte[] readStream(InputStream inputStream) throws Exception {          ByteArrayOutputStream bout = new ByteArrayOutputStream();          byte[] buffer = new byte[1024];          int len = 0;          while ((len = inputStream.read(buffer)) != -1) {              bout.write(buffer, 0, len);          }          bout.close();          inputStream.close();          return bout.toByteArray();      }    }  





源碼地址:http://download.csdn.net/detail/u011732740/8854953

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

Android通過HttpURLConnection擷取JSON並進行UI更新

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.