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

发布于 2025-01-08 19:11:26 字数 623 浏览 0 评论 0原文

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);
        in = response.getEntity().getContent();
        return in;
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        client.close();
    }
}

I put the this method in a Util class.
But when call getInputStream() in another class,I can't get the InputSteam because of AndroidHttpClient is closed.
if I don't close AndroidHttpClient, there appeared "leak found,AndroidHttpClient created and never closed".
How to get the content in this situation

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

扛起拖把扫天下 2025-01-15 19:11:26

像这样,例如:

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

Like this, for instance:

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();
    }
}
伏妖词 2025-01-15 19:11:26

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

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

将以上行包含在您的 Androidmanifest.xml 中

Check whether you have enabled the INTERNET Permission on your manifest file.

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

Include the above line in your Androidmanifest.xml

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文