HttpRequestBase - 如何使用其所有数据打印请求

时间:2013-09-11 14:39:43

标签: java http tostring

我正在使用HttpRequestBase,我想在使用之前将请求完全记录到日志文件中。

默认的toString只返回请求行,我想打印所有标题,参数,请求正文......等等。

有办法吗?

2 个答案:

答案 0 :(得分:16)

HttpRequestBase对象(HttpGetHttpPost等)包含有关标题,参数和实现类包含正文的信息,但它实际上并未序列化为{ {1}}。当String实际发送请求时会发生这种情况。

您可以使用http组件logging configuration

或者你可以调用适当的方法并自己动手。

HttpClient

对于正文,您需要转换为实现类并获取HttpRequestBase base = new HttpGet("www.google.com"); Header[] headers = base.getAllHeaders(); // iterate and print (如果有)。

HttpEntity

并打印它(HttpEntity entity = ((HttpPost)base).getEntity(); // example 内容)。 注意:这可能会占用实体。

完整示例

InputStream

打印

HttpPost post = new HttpPost("www.google.com");
post.setHeader(new BasicHeader("User-Agent", "random client"));
HttpEntity entity = new StringEntity("yellaworld");
post.setEntity(entity);
Header[] headers = post.getAllHeaders();
String content = EntityUtils.toString(entity);

System.out.println(post.toString());
for (Header header : headers) {
    System.out.println(header.getName() + ": " + header.getValue());
}
System.out.println();
System.out.println(content);

答案 1 :(得分:2)

这有效

private void printRequest() {
            System.out.println("receive " + httpRequest.getMethod() +" notification for "+ httpRequest.getRequestURI());


            System.out.println(" \n\n Headers");

            Enumeration headerNames = httpRequest.getHeaderNames();
            while(headerNames.hasMoreElements()) {
                String headerName = (String)headerNames.nextElement();
                System.out.println(headerName + " = " + httpRequest.getHeader(headerName));
            }

            System.out.println("\n\nParameters");

            Enumeration params = httpRequest.getParameterNames();
            while(params.hasMoreElements()){
                String paramName = (String)params.nextElement();
                System.out.println(paramName + " = " + httpRequest.getParameter(paramName));
            }

            System.out.println("\n\n Row data");
            System.out.println(extractPostRequestBody(httpRequest));
        }

        static String extractPostRequestBody(HttpServletRequest request) {
            if ("POST".equalsIgnoreCase(request.getMethod())) {
                Scanner s = null;
                try {
                    s = new Scanner(request.getInputStream(), "UTF-8").useDelimiter("\\A");
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return s.hasNext() ? s.next() : "";
            }
            return "";
        }