Mega Code Archive

 
Categories / Android / Network
 

Get Http Stream

//package com.dedrake.kswine; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; import android.graphics.Bitmap; import android.graphics.BitmapFactory; class Utilities {   public static InputStream getHttpStream(String urlString) throws IOException {     InputStream in = null;     int response = -1;                     URL url = new URL(urlString);      URLConnection conn = url.openConnection();                       if (!(conn instanceof HttpURLConnection)) { throw new IOException("Not an HTTP connection"); }            try {     HttpURLConnection hcn = (HttpURLConnection) conn;     hcn.setAllowUserInteraction(false);     hcn.setInstanceFollowRedirects(true);     hcn.setRequestMethod("GET");     hcn.connect();     response = hcn.getResponseCode();     if (response == HttpURLConnection.HTTP_OK) { in = hcn.getInputStream(); }   }     catch (Exception ex) {       throw new IOException("Error connecting");                 }          return in;        }      public static Bitmap getUrlImage(String urlString) {             Bitmap bmp = null;     InputStream in = null;          try {       in = getHttpStream(urlString);       bmp = BitmapFactory.decodeStream(in);       in.close();     }      catch (IOException e) {     }          return bmp;                   }      public static String getUrlText(String urlString) {     InputStream in = null;            try {       in = getHttpStream(urlString);     }      catch (IOException e) {       return "";     }            InputStreamReader isr = new InputStreamReader(in);     int charRead;     StringBuilder sb = new StringBuilder();     char[] ib = new char[2000];                    try {       while ((charRead = isr.read(ib)) > 0) {                             String readString = String.copyValueOf(ib, 0, charRead);                             sb.append(readString);         ib = new char[2000];       }       in.close();     }      catch (IOException e) {       return "";     }         return sb.toString();           } }