Base64: java.lang.IllegalArgumentException: Illegal character
2022-09-01 01:04:40
我正在尝试在用户注册后发送确认电子邮件。为此,我使用JavaMail库和Java 8 Base64 util类。
我通过以下方式对用户电子邮件进行编码:
byte[] encodedEmail = Base64.getUrlEncoder().encode(user.getEmail().getBytes(StandardCharsets.UTF_8));
Multipart multipart = new MimeMultipart();
InternetHeaders headers = new InternetHeaders();
headers.addHeader("Content-type", "text/html; charset=UTF-8");
String confirmLink = "Complete your registration by clicking on following"+ "\n<a href='" + confirmationURL + encodedEmail + "'>link</a>";
MimeBodyPart link = new MimeBodyPart(headers,
confirmLink.getBytes("UTF-8"));
multipart.addBodyPart(link);
在哪里:confirmationURL
private final static String confirmationURL = "http://localhost:8080/project/controller?command=confirmRegistration&ID=";
然后在 ConfirmRegistrationCommand 中以如下方式对其进行解码:
String encryptedEmail = request.getParameter("ID");
String decodedEmail = new String(Base64.getUrlDecoder().decode(encryptedEmail), StandardCharsets.UTF_8);
RepositoryFactory repositoryFactory = RepositoryFactory
.getFactoryByName(FactoryType.MYSQL_REPOSITORY_FACTORY);
UserRepository userRepository = repositoryFactory.getUserRepository();
User user = userRepository.find(decodedEmail);
if (user.getEmail().equals(decodedEmail)) {
user.setActiveStatus(true);
return Path.WELCOME_PAGE;
} else {
return Path.ERROR_PAGE;
}
当我尝试解码时:
http://localhost:8080/project/controller?command=confirmRegistration&ID=[B@6499375d
我得到.java.lang.IllegalArgumentException: Illegal base64 character 5b
我试图使用基本的编码/解码器(不是URL),但没有成功。
解决:
问题是下一个 - 在行中:
String confirmLink = "Complete your registration by clicking on following"+ "\n<a href='" + confirmationURL + encodedEmail + "'>link</a>";
我正在对字节数组调用string,所以我应该执行以下操作:
String encodedEmail = new String(Base64.getEncoder().encode(
user.getEmail().getBytes(StandardCharsets.UTF_8)));
感谢Jon Skeet和ByteHamster。