什么GBK,UTF-8都是浮云,乱码得这样。[Base64加密解密]

什么GBK,UTF-8都是浮云,乱码得这样。[Base64加密解密]http://www.bieryun.com/1090.html

相信很多人都会遇到乱码问题。想我当初遇到乱码时也是这里转那边转,配置文件里面改,服务器配置里面改,还用强转,改来改去最后还是乱码。

烦死人了。这不。最近又乱码了。好在上天有好生之德。让土豆我意外知道一个东西。哟呵呵~~~解决乱码不是问题。那就是使用Base64编码,接收时再转码。保证不会出现乱码的问题。为什么?这还用说,base64转码后就不是中文了,而是全英文的~~~不多说了。程序员别的不会,先贴代码。

[java] view plain copy

print?

  1. private static BASE64Encoder encoder = new BASE64Encoder();
  2.     private static BASE64Decoder decoder = new BASE64Decoder();
  3.     /**
  4.      * BASE64 编码
  5.      * 
  6.      * @param s
  7.      * @return
  8.      */
  9.     public static String encodeBufferBase64(byte[] buff)
  10.     {
  11.         return buff == null?null:encoder.encodeBuffer(buff).trim();
  12.     }
  13.     /**
  14.      * BASE64解码
  15.      * 
  16.      * @param s
  17.      * @return
  18.      */
  19.     public static byte[] decodeBufferBase64(String s)
  20.     {
  21.         try
  22.         {
  23.             return s == null ? null : decoder.decodeBuffer(s);
  24.         }
  25.         catch (IOException e)
  26.         {
  27.             e.printStackTrace();
  28.         }
  29.         return null;
  30.     }
  31.     /**
  32.      * base64编码
  33.      * 
  34.      * @param bytes
  35.      *            字符数组
  36.      * @return
  37.      * @throws IOException
  38.      */
  39.     public static String encodeBytes(byte[] bytes) throws IOException
  40.     {
  41.         return new BASE64Encoder().encode(bytes).replace("\n""").replace("\r""");
  42.     }
  43.     /**
  44.      * base64解码
  45.      * 
  46.      * @param bytes
  47.      *            字符数组
  48.      * @return
  49.      * @throws IOException
  50.      */
  51.     public static String decodeBytes(byte[] bytes) throws IOException
  52.     {
  53.         return new String(new BASE64Decoder().decodeBuffer(new String(bytes)));
  54.     }

测试代码如下:

[java] view plain copy

print?

  1. public static void main(String[] args) throws Exception
  2.     {
  3.         String str1="我爱你";
  4.         String s=encodeBufferBase64(str1.getBytes());
  5.         System.out.println(s);
  6.         String strs=new String(decodeBufferBase64(s));
  7.         System.out.println(strs);
  8.     }

控制台显示:

[plain] view plain copy

print?

  1. ztKwrsTj
  2. 我爱你

上面有2种方法编码和解码。只不过第二种去掉了空格。

按需分配。Over~~~

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值