Android和Django服务器传输json数据

连通Android和Django后,今天做的就是让Android从Django得到json数据。

一开始是想简单粗暴地直接在main thread里连接服务器,没想到后台报说不能从main thread里发起http连接,网上查了下发现是从4.0开始的。当然这是很正确的做法,防止ANR的问题,毕竟http连接比较耗时。

既然对线程有限制,于是当下想到最简单的就是直接用new Thread().start来了,但是从程序执行来看,好像这个线程完全没有被执行,还没想明白为什么,如果有大神看到,烦请留言指教,谢谢!

对于Android的多线程还没深入学习,网上的资料好像也不多,刚下了份文档这两天看看。至于这里,因为想起之前用过的FutureTask,于是就用了,贴上代码,给需要的朋友参考。

public UpdateInfo getUpdateInfo(final int urlId) throws Exception {


FutureTask<UpdateInfo> task = new FutureTask<UpdateInfo>(

new Callable<UpdateInfo>() {

public UpdateInfo call() throws Exception {


String path = context.getResources().getString(urlId);

HttpClient client = new DefaultHttpClient();

HttpGet httpGet = new HttpGet(path);


StringBuilder sb = new StringBuilder();

HttpResponse response = client.execute(httpGet);

HttpEntity entity = response.getEntity();


InputStreamReader br = new InputStreamReader(entity

.getContent(), "utf-8");


int b;

while ((b = br.read()) != -1) {

sb.append((char) b);

}


JSONObject jsonObj = new JSONObject(sb.toString());

UpdateInfo info = new UpdateInfo();

info.setVersion(jsonObj.getString("version"));

info.setDescription(jsonObj.getString("description"));

info.setUrl(jsonObj.getString("apkurl"));


return info;

}


});


new Thread(task).start();

try {

return task.get();

} catch (Exception e) {

e.printStackTrace();

}

return null;

}


  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值