本例子中使用的是:HttpURLConnection+Thread+Handler的组合,在 new Thread中通过HttpURLConnection获取JSON数据后并在Handler里对UI界面进行更新。
也可以用过HttpClient ,AsyncTask实现此功能,此处就不说啦。
废话不多少直接上代码了
-------------------------------分割线----------------------------------------
activity_main.xml(只有一个简单TextView,用于展示获取JSON后更新其Text)
MainActivity.java
源码地址:http://download.youkuaiyun.com/detail/u011732740/8854953
也可以用过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://xxxxxxxxxxxxxxxxxxx.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.youkuaiyun.com/detail/u011732740/8854953