开发者

Possible to retrieve full headers or size of headers?

开发者 https://www.devze.com 2023-02-14 10:15 出处:网络
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

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开发者_C百科 to be able to get an accurate representation of how many bytes were used up just by the headers.

Thanks in advance.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号