4

I am trying to take in an arbitrary set of HTTP headers and dump it into a WebResource instance. The WebResource interface allows one to do this with query parameters as it offers both a

        webResource.queryParam(key, value)

and

        webResource.queryParams(MultivaluedMap<String, String> queryMap)

The API however, does not allow the same to be done to headers. There is only one function,

            webResource.header(key, value)

which allows one to enter a key-value pair for an HTTP header, but no function

 webResource.headers(MultivaluedMap<String, String> headersMap)

To solve the problem, I tried to retrieve the builder from WebResource and iterate over it, adding the headers one by one

        WebResource.Builder builder = webResource.getRequestBuilder();
    for(Map.Entry<String, String> headersMapEntry : headersMap.entrySet()){
        builder = builder.header(
                       headersMapEntry.getKey(), headersMapEntry.getValue());
    }

but it doesn't seem to solve my problem.

Does anyone have an idea how I can do a workaround with Jersey so that I can dump an arbitrary map into the headers of my WebResource?

Thanks, David

informatik01
  • 16,038
  • 10
  • 74
  • 104
David Karam
  • 334
  • 3
  • 13
  • How does iterating the map and setting the headers individually not solve the problem? – Christopher Currie Aug 02 '11 at 16:32
  • Hey Christopher, your question is exactly why I'm having such a hard time. I iterate manually using either the code above or "webResource.getRequestBuilder().header(key, value);" and with either it does not set the header correctly (I check the outgoing packets being sent on Wireshark) the getRequestBuilder() in the source code of Jersey is merely "return new Builder()", which makes one doubtful about doing it, but if you check all other functions which return a Builder (cookie(), entity, ...), they also use getRequestBuilder(). – David Karam Aug 04 '11 at 08:35

3 Answers3

5

It turned out that the only way around it is to first extract the requestBuilder from the webResource using getRequestBuilder(), and then using requestBuilder to build and execute the rest of the request.

David Karam
  • 334
  • 3
  • 13
  • No clue. Haven't worked with that since a long time. Though I remember it being an utter surprise. Would love to go back and check it out again. – David Karam Nov 28 '13 at 20:57
1

This post explains this problem and solution more thoroughly with examples: http://juristr.com/blog/2015/05/jersey-webresource-ignores-headers/

Peter
  • 5,556
  • 3
  • 23
  • 38
0

Because you can't fire the actual request if you retrieved RequestBuilder or PartialRequestBuilder, you have to retrieve:

WebResource.Builder builder = webResource.getRequestBuilder();

WebResource.Builder has get, post, etc.:

response = builder.post(ClientResponse.class, body);
Akos K
  • 7,071
  • 3
  • 33
  • 46