使用WebServiceTemplate设置自定义标题

时间:2018-07-20 11:58:50

标签: java spring spring-boot

我在春季启动时使用了WebServiceTemplate,并使用marshalSendAndReceive调用了目标服务。

如何在请求中设置自定义HTTP标头?

1 个答案:

答案 0 :(得分:1)

创建消息后,需要使用WebServiceMessageCallback来修改消息。

 webServiceTemplate.marshalSendAndReceive(o, new WebServiceMessageCallback() {

        public void doWithMessage(WebServiceMessage message) {
            try {
                SoapMessage soapMessage = (SoapMessage)message;
                SoapHeader header = soapMessage.getSoapHeader();
                StringSource headerSource = new StringSource("<credentials xmlns=\"http://google.com/profile\">\n +
                        <token>"+customToken"+</token>\n +
                        </credentials>");
                Transformer transformer = TransformerFactory.newInstance().newTransformer();
                transformer.transform(headerSource, header.getResult());
            } catch (Exception e) {
                // something went wrong
            }
        }
    });

因此,从本质上讲,我们正在将Web服务消息转换为SoapMessage以修改标头。