Android – Retrieve InputStream from Web through HTTP

By -

In almost all the normal application, we have to make a WebService call to fetch response and display it. Here is a snippet to make a call on web to fetch/retrieve the response. It will fetch the InputStream and if you want to display result as a string then you have to convert InputStream into String.

Problem: How to retrieve/get InputStream from Web through HTTP?

   private InputStream retrieveStream(String url) {

        DefaultHttpClient client = new DefaultHttpClient();
        HttpGet httpRequest = new HttpGet(url);

        try {

           HttpResponse httpResponse = client.execute(httpRequest);
           final int statusCode = httpResponse.getStatusLine().getStatusCode();

           if (statusCode != HttpStatus.SC_OK) {
                  "Error => " + statusCode + " => for URL " + url);
              return null;

           HttpEntity httpEntity = httpResponse.getEntity();
           return httpEntity.getContent();

        catch (IOException e) {
           Log.w(getClass().getSimpleName(), "Error for URL =>" + url, e);

        return null;

For example:
I included retrieveStream() and iStream_to_String() in my Activity class, and then I wrote the below code to fetch response. In short, in above function you just have to just pass the URL from which you want to retrieve response.

  InputStream is = retrieveStream(myURL);
  System.out.println("Retrieved strings => "+iStream_to_String(is));
Paresh Mayani

Lazy android developer, exploring the horizon of android development since 7 years, currently working as a Technical Lead - Android at Simform Solutions, India. Former Application Architect at KarConnect. He is the Head/Organizer of Google Developers Group (GDG), Ahmedabad

Loading Facebook Comments ...
Loading Disqus Comments ...