Android和Django服务器传输json数据

来源:互联网 发布:trackpad windows 编辑:程序博客网 时间:2024/05/18 03:56

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

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

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

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

public UpdateInfo getUpdateInfo(finalint 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();

}

returnnull;

}


0 0
原创粉丝点击