目录

Java-根据URL获取网络文件并转换成Base64编码工具类

Java–根据URL获取网络文件并转换成Base64编码工具类


import com.google.common.base.Strings;
import org.apache.commons.codec.binary.Base64;
import sun.misc.BASE64Encoder;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**

- @author zhujialin
- @date 2020/7/28
  _/
  public class ConverUtils {
  /**
  _ 根据文件 url 获取文件并转换为 base64 编码 *
  _ @param srcUrl 文件地址
  _ @param requestMethod 请求方式("GET","POST")
  _ @return 文件 base64 编码
  _/
  public static String netSourceToBase64(String srcUrl,String requestMethod) {
  ByteArrayOutputStream outPut = new ByteArrayOutputStream();
  byte[] data = new byte[1024 * 8];
  try {
  // 创建 URL
  URL url = new URL(srcUrl);
  // 创建链接
  HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  conn.setRequestMethod(requestMethod);
  conn.setConnectTimeout(10 * 1000);

              if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
                  //连接失败/链接失效/文件不存在
                  return null;
              }
              InputStream inStream = conn.getInputStream();
              int len = -1;
              while (-1 != (len = inStream.read(data))) {
                  outPut.write(data, 0, len);
              }
              inStream.close();
          } catch (IOException e) {
              e.printStackTrace();
          }
          // 对字节数组Base64编码
          BASE64Encoder encoder = new BASE64Encoder();
          return encoder.encode(outPut.toByteArray());
      }

      /**
       * 把base64转化文件流
       *
       * @param base64 base64
       * @return byte[] 文件流
       */
      public static byte[] decryptByBase64(String base64) {

          if (Strings.isNullOrEmpty(base64)) {
              return null;
          }
          return Base64.decodeBase64(base64.substring(base64.indexOf(",") + 1));
      }

      /**
       * inputStream转化为byte[]数组
       * @param input InputStream
       * @return byte[]
       * @throws IOException
       */
      public static byte[] toByteArray(InputStream input) throws IOException {
          ByteArrayOutputStream output = new ByteArrayOutputStream();
          byte[] buffer = new byte[4096];
          int n = 0;
          while (-1 != (n = input.read(buffer))) {
              output.write(buffer, 0, n);
          }
          return output.toByteArray();
      }

}