Monday 28 October 2013

How to decode a URL image link to a Base64 image string

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import sun.misc.BASE64Encoder;

public class DecodeLinkURL {
    public DecodeLinkURL() {
        super();
    }


  public static String getBase64FromLink(String inputURL) throws Exception{
 
  try {
     
    DefaultHttpClient client = new DefaultHttpClient();
    HttpGet request = new HttpGet(inputURL);
    HttpResponse response;
    response = client.execute(request);

    // Get the response
    BufferedInputStream bis = new BufferedInputStream(response.getEntity().getContent());
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
   
    byte[] chunk = new byte[1024];
    int read;
    do {
      read = bis.read(chunk);
        if (read >= 0) {
          bos.write(chunk, 0, read);
        }
    } while (read >= 0);
   
    BASE64Encoder encoder = new BASE64Encoder();
    String output = encoder.encode(bos.toByteArray());
   
    System.out.println(output);
   
    bos.close();
    bis.close();
     
    return output;
     
  } catch (Exception e) {
      e.printStackTrace();
      throw e;
  }
 
}

    public static void main(String[] args) throws Exception {
        DecodeLinkURL decodeLink = new DecodeLinkURL();
        String stringURL = "www.seedsindia.org/pdf_file/1008904462sample.pdf?";
        String Base64Out = decodeLink.getBase64FromLink(stringURL);
        System.out.println("Base64 String; " + Base64Out);
       
    }
}

No comments:

Post a Comment