• Java中文与Base64互转(解决中文乱码的问题)


    最近线上出现一个问题,前后端交互时,某些情况下,会有中文乱码的问题。

    解决思路:

            1. 在后端先将中文转为 Base64 后再传递到前端(此中文在前端不做显示处理)。

            2. 前端将参数再传递回后端时,后端解析 Base64 得到中文字符串。

    1. package gov.zhbs.utils;
    2. import org.apache.axiom.util.base64.Base64Utils;
    3. import org.apache.commons.lang3.StringUtils;
    4. import org.slf4j.Logger;
    5. import org.slf4j.LoggerFactory;
    6. import java.nio.charset.StandardCharsets;
    7. import java.util.regex.Pattern;
    8. /**
    9. *

    10. *
    11. *

    12. *

    13. * Copyright:.All rights reserved.
    14. *

    15. *

    16. * Company:Zsoft
    17. *

    18. *

    19. * CreateDate: 2022-08-16
    20. *

    21. *
    22. * @author YuGongWen
    23. * @history Mender: YuGongWen;Date: 2022-08-16;
    24. */
    25. public class MyBase64Utils {
    26. private static Logger logger = LoggerFactory.getLogger(MyBase64Utils.class);
    27. /**
    28. * 获取字符串的 Base64 字符串
    29. *
    30. * @param inputStr
    31. * @return
    32. */
    33. public static String getBase64Str(String inputStr) {
    34. if (StringUtils.isBlank(inputStr)) {
    35. return inputStr;
    36. }
    37. String base64Str = Base64Utils.encode(inputStr.getBytes(StandardCharsets.UTF_8));
    38. return base64Str;
    39. }
    40. /**
    41. * 解码 Base64 字符串
    42. *
    43. * @param base64Str
    44. * @return
    45. */
    46. public static String getStrByBase64(String base64Str) {
    47. if (StringUtils.isBlank(base64Str)) {
    48. return base64Str;
    49. }
    50. if (MyBase64Utils.ifBase64Str(base64Str)) {
    51. // nothing to do
    52. } else {
    53. // 非 Base64 格式,不做处理,直接返回
    54. return base64Str;
    55. }
    56. byte[] decode = Base64Utils.decode(base64Str);
    57. return new String(decode, StandardCharsets.UTF_8);
    58. }
    59. /**
    60. * 判断字符串是否为 Base64 格式
    61. *
    62. * @param str
    63. * @return
    64. */
    65. public static boolean ifBase64Str(String str) {
    66. if (StringUtils.isBlank(str)) {
    67. return false;
    68. }
    69. String pattern = "^([A-Za-z0-9+/])*([A-Za-z0-9+/]|[A-Za-z0-9+/]=|[A-Za-z0-9+/])$";
    70. if (Pattern.matches(pattern, str)) {
    71. return true;
    72. } else {
    73. return false;
    74. }
    75. }
    76. }

  • 相关阅读:
    在 Idea 中配置远程 tomcat 并部署
    设计模式(二十九)----综合应用-自定义Spring框架-Spring IOC相关接口分析
    规划兼职工作
    Solidity 小白教程:16. 函数重载
    面试必问的HashCode技术内幕
    前端树形Tree数据结构使用-‍♂️各种姿势总结
    Unity之手游UI的点击和方向移动
    深入解析ASP.NET Core MVC的模块化设计[下篇]
    快来看,数据分析BI软件居然也能完成基金变迁大数据分析?
    Tableau:详细表达式(LOD表达式)的计算过程
  • 原文地址:https://blog.csdn.net/qq_29062045/article/details/126363937