Cookie相关工具方法

    /**
     * InputStream转化为byte[]数组
     * @param input
     * @return
     * @throws IOException
     */
    public static byte[] toByteArray(InputStream input) throws IOException {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        byte[] buffer = new byte[4096];
        int n = 0;
        while (-1 != (n = input.read(buffer))) {
            output.write(buffer, 0, n);
        }
        return output.toByteArray();
    }

    /**
     * 设置Cookie
     * @param response
     * @param key
     * @param value
     */
    public static void setCookie(HttpServletResponse response, String key, String value){
        Cookie cookie = new Cookie(key, value);
        cookie.setPath("/");
        response.addCookie(cookie);
    }

    /**
     * 获取Cookie
     * @param cookies
     * @param key
     * @return
     */
    public static String getCookieByKey(Cookie[] cookies, String key) {
        return getCookieByKey(cookies, key, null);
    }

    /**
     * 获取Cookie
     * @param cookies
     * @param key
     * @param defaultValue
     * @return
     */
    public static String getCookieByKey(Cookie[] cookies, String key , String defaultValue) {
        if (cookies == null || key == null) {return defaultValue;}
        for (Cookie cookie : cookies) {
            if (key.equals(cookie.getName())) {
                return cookie.getValue();
            }
        }
        return defaultValue;
    }

    /**
     * 从Cookie中获取token
     * @param request
     * @param tokenName
     * @return
     */
    public static String getTokenAdaptive(HttpServletRequest request, String tokenName) {
        String token;
        Cookie[] cookies = request.getCookies();
        token = CommonUtil.getCookieByKey(cookies, tokenName);
        if (Strings.isNullOrEmpty(token)){
            token = request.getHeader(tokenName);
        }
        return token;
    }
原文地址:https://www.cnblogs.com/it-deepinmind/p/11805170.html