Wednesday, September 17, 2008

Accessing HTTP Request information with in a web service in Apache Axis2

Sometimes you need to access the HTTP request information within the business logic of your web service. With Axis2, is this trivial as Axis2 keeps the HttpServletRequest as a MessageContext property. We can easily get hold of that extract the necessary information out of it. Here is a simple web service which demonstrates how do it.

Note: This only works in Axis2 war distribution. In standalone Axis2 this doesn't work.


public RequestInfo getInfo() {

// Getting the current MessageContext
MessageContext msgContext = MessageContext.getCurrentMessageContext();

// Getting HttpServletRequest from Message Context
Object requestProperty = msgContext
.getProperty(HTTPConstants.MC_HTTP_SERVLETREQUEST);

RequestInfo info = new RequestInfo();

if (requestProperty != null
&& requestProperty instanceof HttpServletRequest) {

HttpServletRequest request = (HttpServletRequest) requestProperty;

// Extracting the properties from HttpServletRequest filling them in
// RequestInfo bean
info.setRemoteHost(request.getRemoteAddr());
info.setCharacterEncoding(request.getCharacterEncoding());
info.setUserAgent(request.getHeader("user-agent"));
info.setLanguage(request.getLocale().getLanguage());

}

return info;
}


If you invoke this service via web browser, the output will be something like this.
http://localhost:9090/axis2 /services/RequestInfoService/getInfo







or you can try this out using soapui.










You can download the complete source of the this web service here. If you want the binary service archive to try this out, it can be downloaded here.

3 comments:

nafi said...

hi aiya is there anyway that i can keep track on the number of requests i get to a service.I am using axis2 on top of tomcat.

Ankur said...

hi

i have some issues , i am getting messagecontext as null, what i need to do.

Ankur said...

i also tried downloadig Axis2 war distribution from http://ws.apache.org/axis2/download/1_3/download.cgi ...it is not downloading completely?? ....