George
George

Reputation: 23

Possible to retrieve full headers or size of headers?

Is it possible for a java servlet to extract the full text of a request header of response header rather than doing the getHeader() method individually? Alternatively, would it be possible to get the full size in bytes of these headers?

Reason I'm asking this is because I want to track the data usage between the servlet and device sending the request, and due to the large amount of requests that will be send from different devices I want to be able to get an accurate representation of how many bytes were used up just by the headers.

Thanks in advance.

Upvotes: 2

Views: 4192

Answers (2)

Ben George
Ben George

Reputation: 1005

The API does not provide a way to get all the headers with a single call - check the Javadocs:

http://download.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html

Here is an example of how you could get all headers (without tedious null checks).

private MultiValueMap getAllHeaders(HttpServletRequest request) {
    MultiValueMap allHeaders = new MultiValueMap();
    List<String> headerNames = Collections.list((Enumeration<String>)request.getHeaderNames());
    for (String headerName : headerNames) {
        allHeaders.putAll(headerName, Collections.list((Enumeration<String>) request.getHeaders(headerName)));
    }

    return allHeaders;
}

Once you are using the Java Servlet models you cannot get the header size in bytes without re-constructing it (ie: iterate over getAllHeaders and append <header name>: <header value>), you will also need to add the boiler plate GET HTTP 1/1.1 etc. Definitely doable if you absolutely need a Java solution, but I get the feeling you should think about pushing this logic out of your java app and into a proxy.

Upvotes: 2

Stephen C
Stephen C

Reputation: 719386

I don't think you can do it. Or at least, not without hacking on the servlet container implementation.

Perhaps you should put a proxy between HTTP client and server and do the measurement there.

Alternatively, get an approximation by integrating the sizes of the headers / fields in the requests and responses. I'd have thought this would get you to within a couple of percent ... which most folks would say is good enough.

Upvotes: 0

Related Questions