How to manually add a cookie to a webservice call

2019-07-29 10:07发布

问题:

I want to connect to a webservice (WS). However, a cookie must be provided in order to interact with this webservice.

So far, here is what I have:

String requiredCookieName = "requiredCookieName";
String requiredCookieValue = getRequiredCookieValue();

// Prepare SOAP message
SOAPMessage soapMessage = MessageFactory.newInstance().createMessage();
soapMessage.getMimeHeaders().addHeader("SOAPAction", getSoapAction());
soapMessage.saveChanges();

// Send SOAP message
SOAPConnection soapConnection = buildSoapConnection();
SOAPBody soapBody = soapConnection
                      // How to add required cookie here before calling WS?
                      .call(soapMessage, getOperationLocation("operationName"))
                      .getSOAPBody();

// Process response...

How can I add the required cookie to the underlying HTTP request to WS?

回答1:

You can do that by adding the corresponding Cookie HTTP header to the message (exactly as you are already doing for the SOAPAction header):

soapMessage.getMimeHeaders().addHeader(
    "Cookie", requiredCookieName + "=" + requiredCookieValue);