Dubbo获取Request、Cookie

RpcContext

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

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

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;
    }

}

你可能感兴趣的:(dubbo,dubbo,java)