首页 > 解决方案 > JAVA 中的 SOAP 请求。如何通过 HEADER

问题描述

我对创建SOAP请求有疑问。我有一个来自命令行的工作请求curl

<?xml version="1.0"?>
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
 <s:Body>
  <u:SetVolume xmlns:u="urn:schemas-upnp-org:service:RenderingControl:1">
   <InstanceID>0</InstanceID>
   <Channel>Master</Channel>
   <DesiredVolume>20</DesiredVolume>
  </u:SetVolume>
 </s:Body>
</s:Envelope> | curl -v -d @-  -H 'SOAPAction: "urn:schemas-upnp-org:service:RenderingControl:1#SetVolume"'  -H 'content-type: text/xml; charset="utf-8"'  http://192.168.0.172:1400/MediaRenderer/RenderingControl/Control

我在 JAVA 中尝试了等效的板条箱

  import javax.xml.namespace.QName;
import javax.xml.soap.*;

public class SOAPClientSAAJ {


    public static void main(String args[]) {
        try {
                MessageFactory mf = MessageFactory.newInstance();
                SOAPMessage sm = mf.createMessage();
                SOAPHeader sh = sm.getSOAPHeader();
                SOAPBody sb = sm.getSOAPBody();
                sh.detachNode();

                QName bodyName = new QName("urn:schemas-upnp-org:service:RenderingControl:1#SetVolume", "SetVolume", "u");
                SOAPBodyElement bodyElement = sb.addBodyElement(bodyName);

                QName instanceID = new QName("InstanceID");
                QName channel = new QName("Channel");
                QName volumeLevel = new QName("DesiredVolume");

                SOAPElement qInstanceID = bodyElement.addChildElement(instanceID);
                SOAPElement qChannel = bodyElement.addChildElement(channel);
                SOAPElement qVolumeLevel = bodyElement.addChildElement(volumeLevel);

                qInstanceID.addTextNode("0");
                qChannel.addTextNode("Master");
                qVolumeLevel.addTextNode("30");

                sm.writeTo(System.out);
                System.out.println();
        } catch(Exception e) {

        }
    }
}

这给了我构建请求

<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
   <SOAP-ENV:Body>
      <u:SetVolume xmlns:u="urn:schemas-upnp-org:service:RenderingControl:1#SetVolume">
         <InstanceID>0</InstanceID>
         <Channel>Master</Channel>
         <DesiredVolume>30</DesiredVolume>
      </u:SetVolume>
   </SOAP-ENV:Body>
</SOAP-ENV:Envelope>

不幸的是,这不想工作。我认为问题出在 HEADER 中,但实际上我不知道如何以其他方式将它们传递给我的请求。我也尝试从解决方案,但也得到错误

使用 java 对 WebService 的 SOAP 请求

标签: javasoap

解决方案


您似乎设置了错误的 QName。您正在设置的是操作,除了您生成的肥皂信封很好之外,我建议您尝试使用 SOAP UI 调用它。


推荐阅读