android url回调json,Android从url解析json并将其存储起来

本文介绍如何使用异步任务处理耗时的HTTP请求,以避免阻塞主线程。jsonLoad类演示了如何下载JSON数据并将其保存到本地文件,以便后续快速访问。涉及的技术包括DefaultHttpClient、AsyncTask和JSON解析。
摘要由CSDN通过智能技术生成

由于http请求很耗时,所以使用异步任务将是最好的主意。否则,主线程可能会抛出错误。下面显示的类可以异步下载

private class jsonLoad extends AsyncTask {

@Override

protected String doInBackground(String... urls) {

String response = "";

for (String url : urls) {

DefaultHttpClient client = new DefaultHttpClient();

HttpGet httpGet = new HttpGet(url);

try {

HttpResponse execute = client.execute(httpGet);

InputStream content = execute.getEntity().getContent();

BufferedReader buffer = new BufferedReader(new InputStreamReader(content));

String s = "";

while ((s = buffer.readLine()) != null) {

response += s;

}

} catch (Exception e) {

e.printStackTrace();

}

}

return response;

}

@Override

protected void onPostExecute(String result) {

// Instantiate a JSON object from the request response

try {

JSONObject jsonObject = new JSONObject(result);

} catch (JSONException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

File file = new File(getApplicationContext().getFilesDir(),"nowList.cache");

try {

file.createNewFile();

FileOutputStream writer = openFileOutput(file.getName(), Context.MODE_PRIVATE);

writer.write(result);

writer.flush();

writer.close();

}

catch (IOException e) { e.printStackTrace(); return false; }

}

}

与其他答案不同,此处下载的json字符串本身保存在文件中。所以序列化是没有必要的 现在正在加载从URL的JSON可以做到通过调用

jsonLoad jtask=new jsonLoad();

jtask.doInBackground("http:www.json.com/urJsonFile.json");

这将内容保存到文件中。 打开保存的json字符串

File file = new File(getApplicationContext().getFilesDir(),"nowList.cache");

StringBuilder text = new StringBuilder();

try {

BufferedReader br = new BufferedReader(new FileReader(file));

String line;

while ((line = br.readLine()) != null) {

text.append(line);

text.append('\n');

}

br.close();

}

catch (IOException e) {

//print log

}

JSONObject jsonObject = new JSONObject(text);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值