🎉工作中遇到这样一个场景:远程调用某个接口,该接口需要用户的
Cookie
信息进行权限认证,认证通过之后才可以打通并返回数据。
在后端拿到 httpServletRequest
后,调用 getCookies()
方法,返回的是一个 Cookie
类型的数组。Debug 过程中拿到的 cookie
数据结构如下所示:
因此,需要将数组格式转换为字符串形式,核心代码如下:
private String getCookies(HttpServletRequest request) {
try {
Cookie[] cookies = request.getCookies();
// 将Cookie对象数组转换成字符串形式的Cookie
if (!CoreTool.isEmpty(cookies)) {
// 使用数组流处理
return Arrays.stream(cookies)
.map(cookie -> cookie.getName() + "=" + cookie.getValue())
.collect(Collectors.joining("; "));
}
} catch (Exception e) {
LOGGER.error("获取cookie异常", e);
}
return "";
}
类型转换后返回一个字符串格式的 cookie,其内容和在网页端看到的 cookie 内容一致,处理后的 cookie 具体内容以及截图如下:
sensorsdata2015jssdkcross=%7B%22distinct_id%22%3A%22KQm5bczi%22%2C%22first_id%22%3A%22184e11a69c8129e-09ca8d731cb9b28-26021851-1327104-184e11a69c9128b%22%2C%22props%22%3A%7B%22%24latest_traffic_source_type%22%3A%22%E7%9B%B4%E6%8E%A5%E6%B5%81%E9%87%8F%22%2C%22%24latest_search_keyword%22%3A%22%E6%9C%AA%E5%8F%96%E5%88%B0%E5%80%BC_%E7%9B%B4%E6%8E%A5%E6%89%93%E5%BC%80%22%2C%22%24latest_referrer%22%3A%22%22%7D%2C%22identities%22%3A%22eyIkaWRlbnRpdHlfbG9naW5faWQiOiJLUW01YmN6aSIsIiRpZGVudGl0eV9jb29raWVfaWQiOiIxODRlMTFhNjljODEyOWUtMDljYThkNzMxY2I5YjI4LTI2MDIxODUxLTEzMjcxMDQtMTg0ZTExYTY5YzkxMjhiIn0%3D%22%2C%22history_login_id%22%3A%7B%22name%22%3A%22%24identity_login_id%22%2C%22value%22%3A%22KQm5bczi%22%7D%2C%22%24device_id%22%3A%22184e11a69c8129e-09ca8d731cb9b28-26021851-1327104-184e11a69c9128b%22%7D; sso-token=eyJhbGciOiJIUzI1NiJ9.eyJkZXBhcnRtZW50TmFtZSI6IuWfuuehgOW5s-WPsOe7hCIsImNsaWVudElkIjpudWxsLCJkVXNlcklkIjoiMTgwODI4MTgyMzM3NjEzMzIxIiwidXNlckFjY291bnQiOiJTQzg2MDQiLCJ1c2VyUGhvbmUiOiIxMzU1Mjg2NjY4NSIsImRlcGFydG1lbnRDb2RlIjoiMDI0NTA1MDEiLCJwYXJ0RGVwYXJ0bWVudExpc3QiOm51bGwsInVzZXJFbWFpbCI6Inpob25naHVhLmNoZW5Ad2JzdGFyLmNvbSIsInVzZXJOYW1lIjoi6ZmI5Lit5Y2OIiwiZXhwIjoxNjkzNDgzNTUwLCJ1c2VySWQiOiIzODE3ZmQ5Ni05Y2U5LTRkY2UtODUzMi0wMDNjYzE0YTRkMzcifQ.iRnQquAVvzfJtAX6AUtQGpMe94xLr0bG4EIdykC9idI