JAVA中的SOAP请求。如何通过HEADER

时间:2019-01-03 10:55:17

标签: java soap

我对创建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中,但实际上我不知道如何将它们以其他方式传递给我的请求。我也尝试从中解决,但也会出错

SOAP request to WebService with java

1 个答案:

答案 0 :(得分:0)

似乎您设置了错误的QName。您正在设置的是动作,因此除了生成的肥皂包很好之外,我建议您尝试使用SOAP UI进行调用。