How do I print the content of httprequest request?
Asked Answered
V

7

47

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 HttpGet like this:

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?

Verbiage answered 22/9, 2013 at 13:23 Comment(0)
J
103

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

request is the instance of HttpServletRequest

You can beautify the outputs as you desire.

Judson answered 22/9, 2013 at 13:26 Comment(4)
Tip: also specify the type of the Enumeration (e.g. Enumeration<String>) to avoid unwanted IDE errors and make use of generics properly.Apostolic
Adding Enumeration<String> also makes the cast to String unnecessary.Pirtle
Or perhaps Enumeration<?>Copro
To avoid hasMoreElements() and nextElement() as being separate statements, the Enumeration can be converted to a List: for (String headerName : Collections.list(request.getHeaderNames())).Shred
H
12

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();
}
Higgs answered 13/8, 2018 at 11:53 Comment(0)
O
1

In case someone also want to dump response like me. i avoided to dump response body. following code just dump the StatusCode and 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();
}
Ottar answered 24/4, 2019 at 9:44 Comment(0)
A
1

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

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 stream solution.

Apperceive answered 17/9, 2019 at 10:49 Comment(3)
Note, the asIterator() is a Java 9+ addition.Eben
@Eben colld you please explain your suggestion with more details?Apperceive
The asIterator() in the req.getParameterNames().asIterator() is a method that is added and is supported in Java 9. Anyone who is using Java 8 cannot use this method.Eben
A
0

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);
}
Armrest answered 15/5, 2018 at 17:0 Comment(0)
A
0

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);
}
Adalard answered 17/7, 2018 at 10:55 Comment(0)
R
0

HttpHeaders class has entrySet method, it is better to use it:

getHeadersAsString(httpRequest.getHeaders());
...
    private static String getHeadersAsString(HttpHeaders httpRequestHeaders) {
        return httpRequestHeaders
                .entrySet()
                .stream()
                .map(pStringListEntry -> pStringListEntry.getKey() + '=' +
                        (pStringListEntry.getValue() != null
                                ? Arrays.toString(pStringListEntry.getValue().toArray())
                                : ""))
                .collect(Collectors.joining("&"));
    }
Respondence answered 8/11, 2023 at 9:55 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.