简体   繁体   中英

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 = http://i.stack.imgur.com/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();

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

The response is not an encoded String, but the raw bytes of the image (ie if you just store the bytes into a file as they come from that stream, you have the image).

If you need it BASE64 encoded, you have to do it yourself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM