ITeye博客

安卓开发 httpclient导致的闪退问题

Cesar28 · 2015-09-01 20:55 · 安卓开发 · 移动开发 · Markdown

今天在安卓上写了一个调用服务器接口的小demo,然后发现多连接几次服务器程序就闪退,想了半天也不知道原因,后来把静态化的httpclient变成每一次请求都初始化一次,就再也没有问题了,这是正常了以后的代码 public Poem getOnePoem() { try { String baseUrl = "http://ip地址:8080/PoemServer/Poem/";

		DefaultHttpClient httpClient = new DefaultHttpClient();
		HttpGet get = new HttpGet(baseUrl+"getOneRandomPoem");
		HttpResponse response= httpClient.execute(get);
		HttpEntity entity = response.getEntity();

		Map<String, String> maps = gson.fromJson(EntityUtils.toString(entity), new TypeToken<Map<String, String>>(){}.getType());
		
		if(maps.get("code").equals("200")){
			Poem poem = gson.fromJson(maps.get("data"), Poem.class);//new TypeToken<Poem>() {}.getType());
			return poem;
		}
		
	} catch (ParseException e) {
		e.printStackTrace();
	} catch (IOException e) {
		e.printStackTrace();
	}
	return null;
}

之前是在类中写了 static DefaultHttpClient httpClient = new DefaultHttpClient(); static HttpGet get = new HttpGet(baseUrl+"getOneRandomPoem"); static HttpResponse response= httpClient.execute(get); static HttpEntity entity = response.getEntity();

然后总是连接几次就闪退,原因是因为在安卓中,进行网络请求要放在线程中,请求太快静态变量不是线程安全的,所以最好将方法加一个线程锁或者是每次请求初始化一次。

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。