Breaking News
Home / Android / Android Snippets / How to get content of Http URL as a String Android?

How to get content of Http URL as a String Android?

  1. package com.livrona.andriod.commons.utils;
  2.  
  3. import java.io.BufferedReader;
  4. import java.io.IOException;
  5. import java.io.InputStream;
  6. import java.io.InputStreamReader;
  7. import java.io.UnsupportedEncodingException;
  8. import java.net.MalformedURLException;
  9. import java.net.URL;
  10. import java.net.URLConnection;
  11.  
  12. public class HttpUtils {
  13.  
  14.   public static String getContents(String url) {
  15.         String contents ="";
  16.  
  17.   try {
  18.         URLConnection conn = new URL(url).openConnection();
  19.  
  20.         InputStream in = conn.getInputStream();
  21.         contents = convertStreamToString(in);
  22.    } catch (MalformedURLException e) {
  23.         Log.v("MALFORMED URL EXCEPTION");
  24.    } catch (IOException e) {
  25.         Log.e(e.getMessage(), e);
  26.    }
  27.  
  28.   return contents;
  29. }
  30.  
  31. private static String convertStreamToString(InputStream is) throws UnsupportedEncodingException {
  32.  
  33.       BufferedReader reader = new BufferedReader(new    
  34.                               InputStreamReader(is, "UTF-8"));
  35.         StringBuilder sb = new StringBuilder();
  36.          String line = null;
  37.          try {
  38.                 while ((line = reader.readLine()) != null) {
  39.                         sb.append(line + "n");
  40.                 }
  41.            } catch (IOException e) {
  42.                 e.printStackTrace();
  43.            } finally {
  44.                 try {
  45.                         is.close();
  46.                 } catch (IOException e) {
  47.                         e.printStackTrace();
  48.                 }
  49.             }
  50.         return sb.toString();
  51.   }
  52. }
[pb_builder]

Check Also

How to check if an Android device can connect to Internet?

The following code snippet shows how to check if an Android device can connect to …

One comment

  1. Line 39 (corrected): sb.append(line).append(“n”);

Leave a Reply