AndroidHttpClient cannot getEntity (). GetContent () after closing

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 this method in a Util class. But when the call to getInputStream () in another class, I can not get the InputSteam due to the closure of AndroidHttpClient. if I do not close AndroidHttpClient, "a detected leak appears, AndroidHttpClient is created and never closes." How to get content in this situation

+4
source share
2 answers

Like this, for example:

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

Check if INTERNET permission is enabled in the manifest file.

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

Include the above line in your Androidmanifest.xml

0
source

Source: https://habr.com/ru/post/1397782/


All Articles