通过 RequestContext.addZuulRequestHeader 将用户信息的 JSON 格式数据传递给后端服务时中文出现了乱码。尝试设置了几个 Zuul 的配置项,没起作用,于是准备将数据改为使用 Base64 格式传递来避免乱码问题。
1. 将 JSON 字符串转为 Base64 格式的字符串:
import org.springframework.util.Base64Utils;
ctx.addZuulRequestHeader(RequestHeader.SSO_TOKEN,
Base64Utils.encodeToString(
objectMapper.toJSONString(ssoToken).getBytes(StandardCharsets.UTF_8)
)
);
2. 读取 Base64 格式的字符串转为 JSON 格式字符串:
import org.springframework.util.Base64Utils;
String tokenBase64 = request.getHeader(RequestHeader.SSO_TOKEN);
if (StringUtils.isNotEmpty(tokenBase64)) {
String tokenJson = new String(
Base64Utils.decodeFromString(tokenBase64),
StandardCharsets.UTF_8
);
SsoToken ssoToken = objectMapper.parseObject(tokenJson, SsoToken.class);
}
项目中没有 Base64Utils 工具类时可以使用 java.util.Base64 类来实现,示例代码如下:
import java.util.Base64;
String originalString = "Hello World!";
// 将字符串编码为 Base64
String encodedString = Base64.getEncoder().encodeToString(originalString.getBytes(StandardCharsets.UTF_8));
System.out.println("Encoded string: " + encodedString);
// 将 Base64 编码解码为字符串
byte[] decodedBytes = Base64.getDecoder().decode(encodedString);
String decodedString = new String(decodedBytes, StandardCharsets.UTF_8);
System.out.println("Decoded string: " + decodedString);
另外还搜到一种方案:通过 URLEncoder 对字符串编码,然后再通过 URLDecoder 解码(具体方法见这篇博客)。
编码:
RequestContext.getCurrentContext().addZuulRequestHeader("user", URLEncoder.encode(JSONObject.toJSONString(obj), "UTF-8") );解码:
String userStr = this.getRequest().getHeader("user"); User user = null; if (StringUtil.isNotNull(userStr)) { try { user = URLDecoder.decode(userStr, "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } }
版权声明:本文为博主「佳佳」的原创文章,遵循 CC 4.0 BY-NC-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:www.liujiajia.me/2023/6/26/a…