45

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?

Arsen Zahray
  • 24,367
  • 48
  • 131
  • 224

6 Answers6

101

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.

Juned Ahsan
  • 67,789
  • 12
  • 98
  • 136
11

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();
}
Witold Kaczurba
  • 9,845
  • 3
  • 58
  • 67
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();
}
RyanShao
  • 429
  • 2
  • 9
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.

Grigory Kislin
  • 16,647
  • 10
  • 125
  • 197
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);
}
Mike
  • 14,010
  • 29
  • 101
  • 161
Jajikanth pydimarla
  • 1,512
  • 13
  • 11
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);
}
Mike
  • 14,010
  • 29
  • 101
  • 161
PbxMan
  • 7,525
  • 1
  • 36
  • 40