java: 未报告的异常错误java.io.UnsupportedEncodingException; 必须对其进行捕获或声明以便抛出。问题解决。

原问题代码:

/**

  • MD5编码相关的类
  • @author wangjingtao

*/ public class MD5 { // 首先初始化一个字符数组,用来存放每个16进制字符 private static final char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };

/**
 * 获得一个字符串的MD5值
 * 
 * @param input 输入的字符串
 * @return 输入字符串的MD5值
 * 
 */
public static String md5(String input) {
    if (input == null)
        return null;

    try {
        // 拿到一个MD5转换器(如果想要SHA1参数换成”SHA1”)
        MessageDigest messageDigest = MessageDigest.getInstance("MD5");
        // 输入的字符串转换成字节数组
        byte[] inputByteArray = input.getBytes("utf-8");
        // inputByteArray是输入字符串转换得到的字节数组
        messageDigest.update(inputByteArray);
        // 转换并返回结果,也是字节数组,包含16个元素
        byte[] resultByteArray = messageDigest.digest();
        // 字符数组转换成字符串返回
        return byteArrayToHex(resultByteArray);
    } catch (NoSuchAlgorithmException e) {
        return null;
    }
解决后代码:
public static String md5(String input)
{
if (input == null)
return null;
try {
// 拿到一个MD5转换器(如果想要SHA1参数换成”SHA1”)
MessageDigest messageDigest = MessageDigest.getInstance("MD5"); // 输入的字符串转换成字节数组
byte[] inputByteArray = input.getBytes("utf-8"); // Specify the encoding here // inputByteArray是输入字符串转换得到的字节数组
messageDigest.update(inputByteArray); // 转换并返回结果,也是字节数组,包含16个元素
byte[] resultByteArray = messageDigest.digest(); // 字符数组转换成字符串返回
return byteArrayToHex(resultByteArray);
}
catch (NoSuchAlgorithmException | UnsupportedEncodingException e)
{
e.printStackTrace();
// Handle the exception according to your application's requirements return null;
}
}
 
posted @ 2023-12-02 17:05  STDU_DREAM  阅读(349)  评论(0编辑  收藏  举报