How do I print the content of httprequest request?

后端 未结 6 448
名媛妹妹
名媛妹妹 2021-01-31 15:04

I\'ve got a bug involving httprequest, which happens sometimes, so I\'d like to log HttpGet and HttpPost request\'s content when that happens.

So, let\'s say, I create H

6条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-31 15:34

    This should be more helpful for debug. Answer from @Juned Ahsan will not specify full URL and will not print multiple headers/parameters.

    private String httpServletRequestToString(HttpServletRequest request) {
        StringBuilder sb = new StringBuilder();
    
        sb.append("Request Method = [" + request.getMethod() + "], ");
        sb.append("Request URL Path = [" + request.getRequestURL() + "], ");
    
        String headers =
            Collections.list(request.getHeaderNames()).stream()
                .map(headerName -> headerName + " : " + Collections.list(request.getHeaders(headerName)) )
                .collect(Collectors.joining(", "));
    
        if (headers.isEmpty()) {
            sb.append("Request headers: NONE,");
        } else {
            sb.append("Request headers: ["+headers+"],");
        }
    
        String parameters =
            Collections.list(request.getParameterNames()).stream()
                .map(p -> p + " : " + Arrays.asList( request.getParameterValues(p)) )
                .collect(Collectors.joining(", "));             
    
        if (parameters.isEmpty()) {
            sb.append("Request parameters: NONE.");
        } else {
            sb.append("Request parameters: [" + parameters + "].");
        }
    
        return sb.toString();
    }
    

提交回复
热议问题