Dubbo获取Request、Cookie

RpcContext

关于 RpcContext 的理解,详情见:https://blog.csdn.net/sinat_32502451/article/details/134192733

RpcContext是 Dubbo中的一个类,可以用来获取 Context(上下文),接着就能获取到 Request、Cookie。

注意:RpcContext.getContext() 方法,在新版本中,已被替换为 RpcContext.getServiceContext()。

Dubbo获取 Request:

  HttpServletRequest request=  (HttpServletRequest) RpcContext.getContext().getRequest();

Dubbo获取 Cookie数组:

  HttpServletRequest request=  (HttpServletRequest) RpcContext.getContext().getRequest();
  Cookie[] cookies = request.getCookies();

Dubbo获取 Cookie中的值:

public class RpcContextUtil {

    /**
     * 获取cookie中的信息
     * @param key
     * @return
     */
    public static String getFromCookie(String key) {
        String value = "";
        if (StringUtils.isEmpty(key)) {
            return value;
        }
        //获取request
        HttpServletRequest request=  (HttpServletRequest) RpcContext.getContext().getRequest();
        //从request中获取Cookie数组
        Cookie[] cookies = request.getCookies();
        if (cookies == null) {
            return value;
        }
        //从cookie数组中,获取key对应的value
        for (Cookie cookie: cookies) {
            if (key.equals(cookie.getName())) {
                value = cookie.getValue();
            }
        }
        //解码,如果不解码,cookie中的空格有时会乱码显示成%20
        try {
            value = StringUtils.trim(URLDecoder.decode(value, "utf-8"));
        } catch (UnsupportedEncodingException e) {
            log.error("cookie info could not decode.key: {}, value: {}",key, value);
        }
        return value;
    }

}

posted on   乐之者v  阅读(1056)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
历史上的今天:
2018-03-29 Spring知识点提炼
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

导航

统计

点击右上角即可分享
微信分享提示