【问题标题】:AndroidHttpClient can not getEntity().getContent() after closedAndroidHttpClient关闭后无法getEntity().getContent()
【发布时间】:2023-03-16 07:27:01
【问题描述】:
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 创建并且从未关闭”。 这种情况下如何获取内容

【问题讨论】:

    标签: android httpclient inputstream


    【解决方案1】:

    例如这样:

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

    【讨论】:

      【解决方案2】:

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

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

      在您的 Androidmanifest.xml 中包含上述行

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-10-07
        • 2019-06-30
        • 2012-09-24
        • 2019-07-03
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多