Search code examples
javajax-ws

How to get JAX-WS response HTTP status code


When calling a JAX-WS endpoint, how can I get the HTTP response code?

In the sample code bellow, when calling the web service at port.getCustomer(customerID); an Exception may be thrown, such as 401 or 500.

In such cases, how can I get the HTTP status code from the HTTP response?

@Stateless
public class CustomerWSClient {

    @WebServiceRef(wsdlLocation = "/customer.wsdl")
    private CustomerService service;

    public void getCustomer(Integer customerID) throws Exception {
        Customer port = service.getCustomerPort();
        port.getCustomer(customerID); // how to get HTTP status           
    }

}

Solution

  • Completing @Praveen answer, you have to turn the port into a raw BindingProvider and then get the values from the context.

    Don't forget that transaction will be marked for rollback if an exception occours in your managed web service client.

    @Stateless
    public class CustomerWSClient {
    
        @WebServiceRef(wsdlLocation = "/customer.wsdl")
        private CustomerService service;
    
        public void getCustomer(Integer customerID) throws Exception {
            Customer port = service.getCustomerPort();
            try {
                port.getCustomer(customerID);  
            } catch(Exception e) {
                throw e;
            } finally {
                // Get the HTTP code here!
                int responseCode = (Integer)((BindingProvider) port).getResponseContext().get(MessageContext.HTTP_RESPONSE_CODE);
            }
        }
    
    }