如何在 Java 中手动将 cookie 添加到 web 服务调用?

How to manually add a cookie to a webservice call in Java?

我想连接到网络服务 (WS)。但是,必须提供 cookie 才能与此网络服务交互。

到目前为止,这是我所拥有的:

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...

如何将所需的 cookie 添加到 WS 的基础 HTTP 请求中?

您可以通过将相应的 Cookie HTTP header 添加到消息中来做到这一点(就像您已经为 SOAPAction header 所做的一样):

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