使用filter获取http请求的出参以及入参

首先 咱们的目的是作一个拦截器 可以对http请求作profiler,可以记录本次的调用状况,这里说下如何从http请求中获取到出参的问题。html

 

方案一:参照http://blog.csdn.net/wuhenzhangxing/article/details/53079458api

 该方案中,使用了HttpServletResponseWrapper,也就是HttpServletResponse的装饰器,至关一是一个代理,当业务中对response作写入的时候,会被装饰器拦截下来作个处理,好比输出到另外的一个ByteArrayOutputSteam中。而后咱们就能够获取到指定的值了。tomcat

这种方案,使用的是标准的servlet api,比较标准 可是感受仍是有个小麻烦。app

 

方案二:既然反射的功能那么强大  那么咱们能不能用反射来作呢?测试

上代码:spa

    /*获取http出参*/
    private String getOutputSteamContentForTomcat7(ServletResponse response) {
        try {
            OutputStream outputStream = response.getOutputStream();
            Object contentHolder = ReflectUtil.getFiledValue(outputStream, "ob");
            //获取到buffer 而后从buffer中获取到返回值
            Object result = ReflectUtil.getFiledValue(contentHolder, "outputChunk");
            String resultString = result == null ? StringUtils.EMPTY : result.toString();
            if (StringUtils.startsWith(resultString, "<html>")) {
                //含有html文本
                return "HTML-CONTENT";
            }
            return resultString;
        } catch (Exception e) {
            LoggerUtils.error(logger, e, "获取WEB返回内容异常");
            return StringUtils.EMPTY;
        }

该方法中 使用反射来获取,可是坏处也很是明显,因为不是使用的标准的API接口 会致使tomcat版本不一样 内部的类结构不一样而致使获取不到 可是实现起来比较简单。通过测试,对于tomcat6和tomcat7是兼容的 可是tomcat8非兼容.net

相关文章
相关标签/搜索