Search code examples
javaimageencodinggetresponse

Get image from http GET response as base64 String


When my GET request for an image returns an encoded string like ‰PNGØßn¥àí»Ø誯ÐPÒäœ?Å'Üë²...

How can I get the image as a base64 encoded String, instead of whatever encoding this is?

    String url = https://i.sstatic.net/tKsDb.png;

    try{

    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();

    // optional default is GET
    con.setRequestMethod("GET");

    //add request header
    con.setRequestProperty("User-Agent", "Mozilla/5.0");

    int responseCode = con.getResponseCode();
    System.out.println("\nSending 'GET' request to URL : " + url);
    System.out.println("Response Code : " + responseCode);

    BufferedReader in = new BufferedReader(
            new InputStreamReader(con.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();

    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    in.close();
    System.out.println(response.toString());
    //print result
    return response.toString();

Solution

  • Using javax.mail.internet.MimeUtility

    import javax.mail.internet.MimeUtility;
    import java.io.*;
    
    public class Base64Utils {
    
      private Base64Utils() {}
    
      public static byte[] encode(byte[] b) throws Exception {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        OutputStream b64os = MimeUtility.encode(baos, "base64");
        b64os.write(b);
        b64os.close();
        return baos.toByteArray();
      }
    
      public static byte[] decode(byte[] b) throws Exception {
        ByteArrayInputStream bais = new ByteArrayInputStream(b);
        InputStream b64is = MimeUtility.decode(bais, "base64");
        byte[] tmp = new byte[b.length];
        int n = b64is.read(tmp);
        byte[] res = new byte[n];
        System.arraycopy(tmp, 0, res, 0, n);
        return res;
      }
    

    Using Apache Commons

    import org.apache.commons.codec.binary.Base64;
    
    public class Codec {
      public static void main(String[] args) {
        try {
          String clearText = "Hello world";
          String encodedText;
    
          // Base64
          encodedText = new String(Base64.encodeBase64(clearText.getBytes()));
          System.out.println("Encoded: " + encodedText);
          System.out.println("Decoded:"
              + new String(Base64.decodeBase64(encodedText.getBytes())));
          //
          // output :
          //   Encoded: SGVsbG8gd29ybGQ=
          //   Decoded:Hello world
          //
        }
        catch (Exception e) {
          e.printStackTrace();
        }
      }
    }
    

    Using sun.misc.BASE64Encoder

    import java.io.IOException;
    
    import sun.misc.BASE64Decoder;
    import sun.misc.BASE64Encoder;
    
    // Java Base64 Encoder / Java Base64 Decoder Example
    
    public class Base64Test {
    
      public static void main(String[] args) {
        BASE64Decoder decoder = new BASE64Decoder();
        BASE64Encoder encoder = new BASE64Encoder();
        try {
          String encodedBytes = encoder.encodeBuffer("JavaTips.net".getBytes());
          System.out.println("encodedBytes " + encodedBytes);
          byte[] decodedBytes = decoder.decodeBuffer(encodedBytes);
          System.out.println("decodedBytes " + new String(decodedBytes));
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
    

    References: http://www.rgagnon.com/javadetails/java-0598.html http://www.javatips.net/blog/2011/08/how-to-encode-and-decode-in-base64-using-java