1. 程式人生 > >Java從網路中請求獲取JSon資料以及解析JSON資料----(自創,請註明)

Java從網路中請求獲取JSon資料以及解析JSON資料----(自創,請註明)

 Json資料是比較常用的資料型別解析,優點就不多說啦。來看看方法:

public static JSONObject getJsonObject(String url) {
		JSONObject jsonObject = null;
		try {
			
			HttpClient httpClient = new DefaultHttpClient();
			HttpGet httpGet       = new HttpGet(url);
			HttpParams httpParams = httpClient.getParams();
			HttpConnectionParams.setConnectionTimeout(httpParams, 5000);
			HttpResponse response = httpClient.execute(httpGet);
			StringBuilder builder = new StringBuilder();
			BufferedReader bufferedReader = new BufferedReader(
					new InputStreamReader(
							response.getEntity().getContent(), "utf-8"));
			for (String s = bufferedReader.readLine(); s != null; s = bufferedReader
					.readLine()) {
				builder.append(s);
			}
			jsonObject = new JSONObject(builder.toString());
		}catch (Exception e) {
			e.printStackTrace();
			jsonObject = null;
		}
		return jsonObject;
	}

返回的型別即為 JSONObject型別,後續再加入自己的操作就可以了。

注意:此處根據請求的資料量,可能會比較耗時,所以需要用到執行緒來支援,可以使用 AsyncTask,使用的方法為: