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,使用的方法为:

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

得到的Json数据怎么来使用呢,可以参考:JSON学习笔记 GSON解析JSON数据(方便、迅速,含代码)

每个人在他的人生发轫之初,总有一段时光,

Java从网络中请求获取JSon数据以及解析JSON数据

相关文章:

你感兴趣的文章:

标签云: