My Git :?https://github.com/hejiawang
?
一、从服务器端获取json数据,共有两种形式,分别是HttpUrlConnection,和HttpClient(个人喜 ? ? ? ? ? ? ? ? ? ? ? ? 欢HttpUrlConnection)
?
1、HttpUrlConnection的形式,代码如下:
/** * 从指定的URL中获取数组 * @param urlPath * @return * @throws Exception */ public static String 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(); //通过out.Stream.toByteArray获取到写的数据 return new String(outStream.toByteArray()); }
?2、HttpClient的形式,代码如下:
/** * 访问数据库并返回JSON数据字符串 * * @param params 向服务器端传的参数 * @param url * @return * @throws Exception */ public static String doPost(List<NameValuePair> params, String url) throws Exception { String result = null; // 获取HttpClient对象 HttpClient httpClient = new DefaultHttpClient(); // 新建HttpPost对象 HttpPost httpPost = new HttpPost(url); if (params != null) { // 设置字符集 HttpEntity entity = new UrlEncodedFormEntity(params, HTTP.UTF_8); // 设置参数实体 httpPost.setEntity(entity); } /*// 连接超时 httpClient.getParams().setParameter( CoreConnectionPNames.CONNECTION_TIMEOUT, 3000); // 请求超时 httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 3000);*/ // 获取HttpResponse实例 HttpResponse httpResp = httpClient.execute(httpPost); // 判断是够请求成功 if (httpResp.getStatusLine().getStatusCode() == 200) { // 获取返回的数据 result = EntityUtils.toString(httpResp.getEntity(), "UTF-8"); } else { Log.i("HttpPost", "HttpPost方式请求失败"); } return result; }
?
二、解析的代码:
/** * 解析 * * @throws JSONException */ private static ArrayList<HashMap<String, Object>> Analysis(String jsonStr)throws JSONException { JSONArray jsonArray = null; // 初始化list数组对象 ArrayList<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>(); jsonArray = new JSONArray(jsonStr); for (int i = 0; i < jsonArray.length(); i++) { JSONObject jsonObject = jsonArray.getJSONObject(i); // 初始化map数组对象 HashMap<String, Object> map = new HashMap<String, Object>(); map.put("a", jsonObject.getString("a")); map.put("b", jsonObject.getString("b")); list.add(map); } return list; }
?其中, map.put("a", jsonObject.getString("a"));中a代表json数据,json数据就不说了。。。。。
?
这样,从服务器上得到的json数据就成了我们熟悉的集合数据了。。。
上面的代码主要用到了两个类:JSONArray和JSONObject?
原文:http://hejiawangjava.iteye.com/blog/2247829