Press "Enter" to skip to content

Add custom HTTP header to an Axis 2 SOAP request

A few days ago I had a challenging task in Java: I had to add a custom header to my SOAP request using Axis 2. But the custom header had to be passed as a HTTP header, not in the SOAP Envelope, since it was used by a Filter and it had nothing to do with the rest of the request. The Filter simply gets a ServletRequest, gets the extra parameter from the HTTP header and does something with it, without having to parse the SOAP Envelope. It’s not that hard to do, there is documentation on this issue, but because there can hardly be found a good example, one may waste several hours trying different solutions.

OK. I had to insert a “Token” parameter in the HTTP header, so my request would look something like this:

POST /services/UserManager HTTP/1.1  
Content-Type: multipart/related; boundary=MIMEBoundaryurn_uuid_E4EC52BDC86F7DFF291336111735437; type="application/xop+xml"; start=""; start-info="text/xml"  
SOAPAction: "urn:getUserPreferences"  
Token: c0c634b8-1c4e-4d39-a82d-1661d357e05b  
User-Agent: Axis2  
Host: localhost:8082  
Transfer-Encoding: chunked  

What I did was create a new org.apache.commons.httpclient.Header with the needed key-value pair and simply set the right property on the Options object. This is bit confusing, because the first thing you would do is to simply set a new property:

serviceClient.getOptions().setProperty("Token", "testToken");  

This is how I wasted a couple of hours and couldn’t manage to get it work how I wanted. Nope, you have to create a list of Headers and update the HTTP_HEADERS property:

List<Header> headers = (List<Header>) serviceClient.getOptions().getProperty(HTTPConstants.HTTP_HEADERS);  
if (headers == null){  
    headers = new ArrayList<Header>();
headers.add(new Header("Token", generateToken()));  
serviceClient.getOptions().setProperty(HTTPConstants.HTTP_HEADERS, headers);  

On the server side you may simply get the parameter:

final String token = ((HttpServletRequest) servletRequest).getHeader("Token");  

It’s really just a few lines of code, nothing complicated. Hope it helps 😉