Setting a custom HTTP header dynamically with Spring-WS client

后端 未结 7 581
我在风中等你
我在风中等你 2020-12-24 05:53

How do you set a custom HTTP header (not SOAP header) dynamically on the client side when using Spring-WS?

7条回答
  •  Happy的楠姐
    2020-12-24 06:36

    Actually, it is an updated version of the @Tomasz's answer, but provides a new Spring-WS API, Java 8 shortcuts, and cares about creating a WebServiceMessageCallback instance with a separate method.

    I believe it is more obvious and self-sufficient.

    final class Service extends WebServiceGatewaySupport {
    
        /**
         * @param URL       the URI to send the message to
         * @param payload   the object to marshal into the request message payload
         * @param headers   HTTP headers to add to the request
         */
        public Object performRequestWithHeaders(String URL, Object payload, Map headers) {
            return getWebServiceTemplate()
                    .marshalSendAndReceive(URL, payload, getRequestCallback(headers));
        }
    
        /**
         * Returns a {@code WebServiceMessageCallback} instance with custom HTTP headers.
         */
        private WebServiceMessageCallback getRequestCallback(Map headers) {
            return message -> {
                TransportContext context = TransportContextHolder.getTransportContext();
                HttpUrlConnection connection = (HttpUrlConnection)context.getConnection();
                addHeadersToConnection(connection, headers);
            };
        }
    
        /**
         * Adds all headers from the {@code headers} to the {@code connection}.
         */
        private void addHeadersToConnection(HttpUrlConnection connection, Map headers){
            headers.forEach((name, value) -> {
                try {
                    connection.addRequestHeader(name, value);
                } catch (IOException e) {
                    e.printStackTrace(); // or whatever you want
                }
            });
        }
    
    }
    

提交回复
热议问题