您的位置:首页 > 理论基础 > 计算机网络

Java从网络中请求获取JSon数据以及解析JSON数据----(自创,请注明)

2015-04-03 16:14 295 查看
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,使用的方法为:

请看我的另一篇博文:AsyncTask的两种使用方法(含代码)

得到的Json数据怎么来使用呢,可以参考:JSON学习笔记 GSON解析JSON数据(方便、迅速,含代码)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: