【问题标题】:Base64 encoding in Java / GroovyJava / Groovy 中的 Base64 编码
【发布时间】:2011-05-10 11:01:18
【问题描述】:

在 Java 中将字节 [] 转换为 Base64 字符串的正确方法是什么?更好的是 Grails / Groovy,因为它告诉我 encodeAsBase64() 函数已被弃用。不推荐使用 sun.misc.BASE64Encoder 包,它在某些 Windows 平台上输出不同大小的字符串。

【问题讨论】:

    标签: java grails encoding groovy base64


    【解决方案1】:

    在 groovy 中执行此操作的首选方法是:

     def encoded = "Hello World".bytes.encodeBase64().toString()
     assert encoded == "SGVsbG8gV29ybGQ="
     def decoded = new String("SGVsbG8gV29ybGQ=".decodeBase64())
     assert decoded == "Hello World"
    

    【讨论】:

    • 这个问题是encodeBase64 在每 76 个字符中添加一行,这会弄乱字符串的长度。我最终使用 def encoded = byteArray.collect { it as char } 而不是 Base64 编码。
    • 默认情况下,从 1.6.0 版本开始,groovy 不会在编码中插入额外的换行符。调用 encodeBase64(true) 会启用该行为。
    【解决方案2】:
    【解决方案3】:

    您可以使用开源的Base64Coder

    import biz.source_code.base64Coder.Base64Coder
    
    @Grab(group='biz.source_code', module='base64coder', version='2010-09-21')
    
    String s1 = Base64Coder.encodeString("Hello world")
    String s2 = Base64Coder.decodeString("SGVsbG8gd29ybGQ=")
    

    【讨论】:

      【解决方案4】:

      像这样实现你自己的方法:)

      public class Coder {
      private static final String base64code = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
      
      public static String encodeAsBase64(String toEncode) {
          return encodeAsBase64(toEncode.getBytes())
      }
      
      public static String encodeAsBase64(byte[] toEncode) {
          int pos = 0;
          int onhand = 0;
      
          StringBuffer buffer = new StringBuffer();
          for(byte b in toEncode) {
              int read = b;
              int m;
              if(pos == 0) {
                  m = (read >> 2) & 63;
                  onhand = read & 3;
                  pos = 1;
              } else if(pos == 1) {
                  m = (onhand << 4) + ((read >> 4) & 15);
                  onhand = read & 15;
                  pos = 2;
              } else if(pos == 2) {
                  m = ((read >> 6) & 3) + (onhand << 2);
                  onhand = read & 63;
                  buffer.append(base64code.charAt(m));
                  m = onhand;
                  onhand = 0;
                  pos  = 0;
              }
              buffer.append(base64code.charAt(m));
          }
          while(pos > 0 && pos < 4) {
              pos++;
              if(onhand == -1) {
                  buffer.append('=');
              } else {
                  int m = pos == 2 ? onhand << 4 : (pos == 3 ? onhand << 2 : onhand);
                  onhand = -1;
                  buffer.append(base64code.charAt(m));
              }
          }
          return buffer.toString()
      }
      

      }

      【讨论】:

        【解决方案5】:

        (将此添加到此线程中,希望其他人会对此有所了解,而不必浪费他宝贵的时间)

        今天当我尝试在我的 Grails 2.3.11/Groovy 2.1.9 应用程序中添加输出时遇到了阻碍

        String src = render(
                model:    ...,
                template: ...,
            )
            .encodeAsBase64()
        

        作为 DOM 元素的 data- 属性。但是相应 JavaScript 中的atob(),即从 data 属性中解码 Base64 字符串的代码,一直抱怨非法字符,而其他解码器,例如base64 -d 接受相同的 Base64 字符串没有问题。

        解决方法是强制render()返回值为单个字符串,然后应用Base64编码,即

        String src = render(
                model:    ...,
                template: ...,
            )
            .toString()
            .encodeAsBase64()
        

        或(如果您认为 encodeAsBase64() 已弃用):

        String src = render(
                model:    ...,
                template: ...,
            )
            .toString()
            .bytes
            .encodeBase64() // add 'true' for chunked output
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-10-18
          • 2015-04-18
          • 2020-04-06
          • 2015-07-21
          • 1970-01-01
          • 2015-05-07
          相关资源
          最近更新 更多