如何打印请求请求的内容?

2022-09-01 00:49:02

我有一个涉及httprequest的错误,有时会发生这种情况,所以我想在发生这种情况时记录HttpGet和HttpPost请求的内容。

所以,比方说,我创建HttpGet是这样的:

HttpGet g = new HttpGet();
g.setURI(new URI("http://www.google.com"));
g.setHeader("test", "hell yeah");

这是我想得到的字符串表示形式:

GET / HTTP/1.1
Host: www.google.com
test: hell yeah

通过发布请求,我还想获取内容字符串。

在Java for android中执行此操作的最简单方法是什么?


答案 1

您可以使用以下命令打印请求类型:

request.getMethod();

您可以打印此处提到的所有标题:

Enumeration<String> headerNames = request.getHeaderNames();
while(headerNames.hasMoreElements()) {
  String headerName = headerNames.nextElement();
  System.out.println("Header Name - " + headerName + ", Value - " + request.getHeader(headerName));
}

要打印所有请求参数,请使用:

Enumeration<String> params = request.getParameterNames(); 
while(params.hasMoreElements()){
 String paramName = params.nextElement();
 System.out.println("Parameter Name - "+paramName+", Value - "+request.getParameter(paramName));
}

requestHttpServletRequest

您可以根据需要美化输出。


答案 2

这对调试应该更有帮助。来自@Juned Ahsan的回答不会指定完整的URL,也不会打印多个标题/参数。

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