SharonBL SharonBL - 3 months ago 11
HTTP Question

HttpRequestBase - How to print the request with all its data

I'm using HttpRequestBase and I want to log the request fully to a log file before using it.

The default toString returns only the request line and I want to print all the headers, parameters, request body etc...

Is there a way to do so?

Answer

The HttpRequestBase object (HttpGet, HttpPost, etc.) contains information about the headers, parameters, and the implementation class contain body, but it's not actually serialized into a String. That happens when the HttpClient actually sends the request.

You can play with the http components logging configuration.

Or you can call the appropriate methods and do it yourself.

HttpRequestBase base = new HttpGet("www.google.com");
Header[] headers = base.getAllHeaders();
// iterate and print

For the body, you need to cast to your implementation class and get the HttpEntity, if it has one.

HttpEntity entity = ((HttpPost)base).getEntity(); // example

And print it (its InputStream content). Note: That might consume the entity.

Full example

HttpPost post = new HttpPost("www.google.com");
post.setHeader(new BasicHeader("User-Agent", "random client"));
HttpEntity entity = new StringEntity("yellaworld");
post.setEntity(entity);
Header[] headers = post.getAllHeaders();
String content = EntityUtils.toString(entity);

System.out.println(post.toString());
for (Header header : headers) {
    System.out.println(header.getName() + ": " + header.getValue());
}
System.out.println();
System.out.println(content);

prints

POST www.google.com HTTP/1.1
User-Agent: random client

yellaworld