Setting a custom HTTP header dynamically with Spring-WS client

后端 未结 7 570
我在风中等你
我在风中等你 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条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-24 06:40

    Spring's webServiceTemplate.marshalSendAndReceive(request) method internally uses HttpComponentsMessageSender to send the SOAP message over the network and this further uses WebServiceConnection to make http connection with the server. All you have to do is to write your own custom HttpComponentsMessageSender and set the cookie inside postMethod.

    Custome sender code:

        package com.swap.ws.sender;
    
    import java.io.IOException;
    import java.net.URI;
    
    import javax.annotation.Resource;
    
    import org.apache.http.client.methods.HttpPost;
    import org.apache.log4j.Logger;
    import org.springframework.stereotype.Service;
    import org.springframework.ws.transport.WebServiceConnect ion;
    import org.springframework.ws.transport.http.HttpComponen tsConnection;
    
    /**
    * 
    * @author swapnil Z
    */
    @Service("urlMessageSender")
    public class CustomHttpComponentsMessageSender extends
    org.springframework.ws.transport.http.HttpComponen tsMessageSender {
    private static Logger _logger = Logger.getLogger("");
    
    
    @Override
    public WebServiceConnection createConnection(URI uri) throws IOException {
    String cookie = null;
    HttpComponentsConnection conn = (HttpComponentsConnection) super
    .createConnection(uri);
    HttpPost postMethod = conn.getHttpPost();
    cookie = "";
    
    postMethod.addHeader("Cookie", cookie);
    
    return conn;
    }
    }
    

    Spring Configuration :

    
    
    
    
    
    
    
    
    
    
    
     />
    
    

    After this I simply get bean webServiceTemplate and call marshalSendAndReceive method. So every request will have its custom cookie set before making HTTP call.

提交回复
热议问题