---
title: "安卓开发 httpclient导致的闪退问题"
author: "Cesar28"
date: "2015-09-01T20:55:06Z"
tags: []
categories: ["移动开发"]
slug: "httpclient"
draft: false
lastmod: "2015-09-01T21:06:05Z"
id: 2240110
url: "https://cesar28.iteye.com/blog/2240110"
---

今天在安卓上写了一个调用服务器接口的小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();

然后总是连接几次就闪退，原因是因为在安卓中，进行网络请求要放在线程中，请求太快静态变量不是线程安全的，所以最好将方法加一个线程锁或者是每次请求初始化一次。