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 已创建但从未关闭”。
这种情况下如何获取内容

最佳答案

像这样,例如:

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();
    }
}

关于AndroidHttpClient 关闭后无法 getEntity().getContent(),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9393426/

10-09 10:16