如何从服务器下载 JSON 的示例?
Posted
技术标签:
【中文标题】如何从服务器下载 JSON 的示例?【英文标题】:Example of how to download JSON from server? 【发布时间】:2010-08-26 18:48:06 【问题描述】:有没有一个很好的例子来说明如何查询服务器和下载响应(JSON 或 XML)?
【问题讨论】:
【参考方案1】:这应该可以解决问题
String JsonResponse = HttpHelper.connect(SERVER_URL);
JSONObject json=new JSONObject(JsonResponse);
private static String convertStreamToString(InputStream is)
/*
* To convert the InputStream to String we use the BufferedReader.readLine()
* method. We iterate until the BufferedReader return null which means
* there's no more data to read. Each line will appended to a StringBuilder
* and returned as String.
*/
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try
while ((line = reader.readLine()) != null)
sb.append(line + "\n");
catch (IOException e)
e.printStackTrace();
finally
try
is.close();
catch (IOException e)
e.printStackTrace();
return sb.toString();
public static String connect(String url)
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
HttpResponse response;
try
response = httpclient.execute(httpget);
//Log.i(TAG,response.getStatusLine().toString());
HttpEntity entity = response.getEntity();
if (entity != null)
InputStream instream = entity.getContent();
String result= convertStreamToString(instream);
instream.close();
return result;
catch (ClientProtocolException e)
catch (IOException e)
return null;
【讨论】:
以上是关于如何从服务器下载 JSON 的示例?的主要内容,如果未能解决你的问题,请参考以下文章
如何使用 phpmyadmin 和 json 从 android 上传和下载图像到服务器?
如何从 api 服务器下载/保存 json 数据并在每个特定时间自动更新?
如何从android中的url解析多个JSON对象和数组?我正在使用一个示例,我希望在该示例中使用它,