AndroidHttpClient关闭后无法getEntity()。getContent()

时间:2012-02-22 10:54:27

标签: android httpclient inputstream

public InputStream getInputStream() {
    AndroidHttpClient client = AndroidHttpClient.newInstance(USERAGENT);
    HttpUriRequest request = new HttpGet(url);
    InputStream in = null;
    try {
        HttpResponse response = client.execute(request);
        in = response.getEntity().getContent();
        return in;
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        client.close();
    }
}

我将此方法放在Util类中。 但是当在另一个类中调用getInputStream()时,由于AndroidHttpClient被关闭,我无法获得InputSteam。 如果我没有关闭AndroidHttpClient,就会出现“发现泄漏,AndroidHttpClient已创建且从未关闭”。 如何在这种情况下获取内容

2 个答案:

答案 0 :(得分:5)

像这样,例如:

public InputStream getInputStream() {
    AndroidHttpClient client = AndroidHttpClient.newInstance(USERAGENT);
    HttpUriRequest request = new HttpGet(url);
    InputStream in = null;
    try {
        HttpResponse response = client.execute(request);
        return new ByteArrayInputStream(new EntityUtils.toByteArray(response.getEntity()));
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        client.close();
    }
}

答案 1 :(得分:0)

检查您是否在清单文件上启用了INTERNET权限。

<uses-permission android:name="android.permission.INTERNET"/> 

在Androidmanifest.xml

中包含上述行