如何获取 JAX-WS 响应 HTTP 状态码

How to get JAX-WS response HTTP status code

调用 JAX-WS 端点时,如何获取 HTTP 响应代码?

在下面的示例代码中,在port.getCustomer(customerID);调用web服务时可能会抛出异常,例如401500

在这种情况下,如何从 HTTP 响应中获取 HTTP 状态代码?

@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           
    }

}

以下post与您的问题类似。希望它对你有用

完成@Praveen 的回答,您必须将 port 转换为原始 BindingProvider,然后从上下文中获取值。

不要忘记,如果您的托管 Web 服务客户端发生异常,事务将被标记为回滚。

@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);
        }
    }

}