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?
Solution:

   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) {
              Log.w(getClass().getSimpleName(),
                  "Error => " + statusCode + " => for URL " + url);
              return null;
           }

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

        }
        catch (IOException e) {
        	httpRequest.abort();
           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));

CEO & Co-Founder at SolGuruz® | Organiser @ GDG Ahmedabad | Top 0.1% over StackOverflow | 15+ years experienced Tech Consultant | Helping startups with Custom Software Development

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