SharonBL SharonBL - 1 year ago 151
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 Source

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("");
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("");
post.setHeader(new BasicHeader("User-Agent", "random client"));
HttpEntity entity = new StringEntity("yellaworld");
Header[] headers = post.getAllHeaders();
String content = EntityUtils.toString(entity);

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


User-Agent: random client

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download