zoukankan      html  css  js  c++  java
  • 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;
        }
  • 相关阅读:
    IDEA 运行junit单元测试方法
    IDEA 修改编码
    接口文档word版
    java 上传文件到七牛云中
    单例模式
    洛谷P3092 [USACO13NOV]没有找零No Change
    Codevs 1159 最大全0子矩阵
    洛谷P2733 家的范围 Home on the Range
    洛谷P2280 [HNOI2003]激光炸弹
    洛谷P2023 [AHOI2009]维护序列
  • 原文地址:https://www.cnblogs.com/it-deepinmind/p/11805170.html
Copyright © 2011-2022 走看看