Base 64 编码和解码示例代码 [英] Base 64 encode and decode example code

查看:54
本文介绍了Base 64 编码和解码示例代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有谁知道如何使用 Base64 解码和编码 Base64 中的字符串.我正在使用以下代码,但它不起作用.

Does anyone know how to decode and encode a string in Base64 using the Base64. I am using the following code, but it's not working.

String source = "password"; 
byte[] byteArray = source.getBytes("UTF-16"); 
Base64 bs = new Base64(); 
//bs.encodeBytes(byteArray); 
System.out.println( bs.encodeBytes(byteArray)); 
//bs.decode(bs.encodeBytes(byteArray));
System.out.println(bs.decode(bs.encodeBytes(byteArray)));

推荐答案

第一:

  • 选择一种编码.UTF-8 通常是一个不错的选择;坚持一种在双方都肯定有效的编码.很少使用 UTF-8 或 UTF-16 以外的其他格式.

发送端:

  • 将字符串编码为字节(例如 text.getBytes(encodingName))
  • 使用 Base64 类将字节编码为 base64
  • 传输 base64
  • Encode the string to bytes (e.g. text.getBytes(encodingName))
  • Encode the bytes to base64 using the Base64 class
  • Transmit the base64

接收端:

  • 接收base64
  • 使用 Base64 类将 base64 解码为字节
  • 将字节解码为字符串(例如new String(bytes, encodingName))
  • Receive the base64
  • Decode the base64 to bytes using the Base64 class
  • Decode the bytes to a string (e.g. new String(bytes, encodingName))

比如:

// Sending side
byte[] data = text.getBytes("UTF-8");
String base64 = Base64.encodeToString(data, Base64.DEFAULT);

// Receiving side
byte[] data = Base64.decode(base64, Base64.DEFAULT);
String text = new String(data, "UTF-8");

或者使用StandardCharsets:

// Sending side
byte[] data = text.getBytes(StandardCharsets.UTF_8);
String base64 = Base64.encodeToString(data, Base64.DEFAULT);

// Receiving side
byte[] data = Base64.decode(base64, Base64.DEFAULT);
String text = new String(data, StandardCharsets.UTF_8);

这篇关于Base 64 编码和解码示例代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆