首页 > 其他 > 详细

Cookie相关工具方法

时间:2019-11-06 15:08:33      阅读:57      评论:0      收藏:0      [点我收藏+]
    /**
     * 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;
    }

 

Cookie相关工具方法

原文:https://www.cnblogs.com/it-deepinmind/p/11805170.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!