Get image from http GET response as base64 String

我怕爱的太早我们不能终老 提交于 2021-02-08 11:32:32

问题


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();

回答1:


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




回答2:


The response is not an encoded String, but the raw bytes of the image (i.e. 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.



来源:https://stackoverflow.com/questions/25883180/get-image-from-http-get-response-as-base64-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!