package com.info.util;java
import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.List;apache
import org.json.JSONArray; import org.json.JSONObject;編程
import com.info.bean.Person;json
public class JsonParse { /** * 解析Json數據 * * @param urlPath * @return mlists * @throws Exception */數組
public static List<Person> getListPerson(String urlPath) throws Exception { List<Person> mlists = new ArrayList<Person>(); byte[] data = readParse(urlPath); JSONArray array = new JSONArray(new String(data)); for (int i = 0; i < array.length(); i++) { JSONObject item = array.getJSONObject(i); String name = item.getString("name"); String address = item.getString("address"); int age = item.getInt("age"); mlists.add(new Person(name, address, age)); } return mlists; } /** * 從指定的url中獲取字節數組 * * @param urlPath * @return 字節數組 * @throws Exception * * Android下的網絡編程 & 代理的使用 * * 1. 使用 標準Java接口: 設計的類: java.net.* 基本步驟: * * 1) 建立 URL 以及 URLConnection / HttpURLConnection 對象 2) 設置鏈接參數 * 3) 鏈接到服務器 4) 向服務器寫數據 * * 5)從服務器讀取數據 * * 2. 使用 apache 接口: Apache HttpClient 是一個開源項目,彌補了 java.net.* * 靈活性不足的缺點, 支持客戶端的HTTP編程. 使用的類包括: org.apache.http.* * * 步驟: 1) 建立 HttpClient 以及 GetMethod / PostMethod, HttpRequest * 等對象; 2) 設置鏈接參數; 3) 執行 HTTP 操做; 4) 處理服務器返回結果. */ public static byte[] readParse(String urlPath) throws Exception { ByteArrayOutputStream outStream = new ByteArrayOutputStream(); byte[] data = new byte[1024]; int len = 0; URL url = new URL(urlPath); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); InputStream inStream = conn.getInputStream(); while ((len = inStream.read(data)) != -1) { outStream.write(data, 0, len); } inStream.close(); return outStream.toByteArray(); }
}服務器