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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18944302/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 12:46:12  来源:igfitidea点击:

How do I print the content of httprequest request?

javaandroidhttp-posthttp-get

提问by Arsen Zahray

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.

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

So, let's say, I create HttpGet like this:

所以,假设我像这样创建 HttpGet:

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

This is the string representation that I'd like to get:

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

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

With the post request, I'd also like to get the content string.

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

What is the easiest way to do it in java for android?

在java for android中最简单的方法是什么?

采纳答案by Juned Ahsan

You can print the request type using:

您可以使用以下方法打印请求类型:

request.getMethod();

You can print all the headers as mentioned here:

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

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

To print all the request params, use this:

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

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

requestis the instance of HttpServletRequest

request是实例 HttpServletRequest

You can beautify the outputs as you desire.

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

回答by Jajikanth pydimarla

More details that help in logging

更多有助于记录的细节

    String client = request.getRemoteAddr();
    logger.info("###### requested client: {} , Session ID : {} , URI :" + request.getMethod() + ":" + request.getRequestURI() + "", client, request.getSession().getId());

    Map params = request.getParameterMap();
    Iterator i = params.keySet().iterator();
    while (i.hasNext()) {
        String key = (String) i.next();
        String value = ((String[]) params.get(key))[0];
        logger.info("###### Request Param Name : {} , Value :  {} ", key, value);
    }

回答by PbxMan

If you want the content string and this string does not have parameters you can use

如果您想要内容字符串并且此字符串没有参数,您可以使用

    String line = null;
    BufferedReader reader = request.getReader();
    while ((line = reader.readLine()) != null){
        System.out.println(line);
    }

回答by Witold Kaczurba

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

这应该对调试更有帮助。@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();
}

回答by RyanShao

In case someone also want to dump response like me. i avoided to dump response body. following code just dump the StatusCode and Headers.

如果有人也想像我一样转储响应。我避免转储响应体。以下代码仅转储 StatusCode 和 Headers。

static private String dumpResponse(HttpServletResponse resp){
    StringBuilder sb = new StringBuilder();

    sb.append("Response Status = [" + resp.getStatus() + "], ");
    String headers = resp.getHeaderNames().stream()
                    .map(headerName -> headerName + " : " + resp.getHeaders(headerName) )
                    .collect(Collectors.joining(", "));

    if (headers.isEmpty()) {
        sb.append("Response headers: NONE,");
    } else {
        sb.append("Response headers: "+headers+",");
    }

    return sb.toString();
}

回答by Grigory Kislin

Rewrite @Juned Ahsan solution via stream in one line (headers are treated the same way):

在一行中通过流重写@Juned Ahsan 解决方案(标题的处理方式相同):

public static String printRequest(HttpServletRequest req) {
    String params = StreamSupport.stream(
            ((Iterable<String>) () -> req.getParameterNames().asIterator()).spliterator(), false)
            .map(pName -> pName + '=' + req.getParameter(pName))
            .collect(Collectors.joining("&"));
    return req.getRequestURI() + '?' + params;
}

See also how to convert an iterator to a streamsolution.

另请参阅如何将迭代器转换为流解决方案。