Search code examples
javaparsingsoapresponse

Can't process SOAP response


I have the following code:

SOAPConnectionFactory sfc = SOAPConnectionFactory.newInstance();
          SOAPConnection connection = sfc.createConnection();

          MessageFactory mf = MessageFactory.newInstance();
          SOAPMessage sm = mf.createMessage();
          SOAPHeader sh = sm.getSOAPHeader();
          SOAPBody sb = sm.getSOAPBody();
          sh.detachNode();
          MimeHeaders mimeHeader = sm.getMimeHeaders();

          //change header's attribute
          mimeHeader.setHeader("SOAPAction", "\"urn:Belkin:service:basicevent:1#GetBinaryState\"");
          //sh.addAttribute(SOAPFactory.newInstance().createName("SOAPAction", "", "urn:Belkin:service:basicevent:1#SetBinaryState"),"");
          QName bodyName = new QName("urn:Belkin:service:basicevent:1", "GetBinaryState", "u");

          //sm.add            

          SOAPBodyElement bodyElement = sb.addBodyElement(bodyName);
          QName qn = new QName("BinaryState");

          System.out.println("\n Soap Request:\n");
          sm.writeTo(System.out);
          System.out.println();

          URL endpoint = new URL("http://" + ipAddress + ":49153/upnp/control/basicevent1");
          SOAPMessage response = connection.call(sm, endpoint);

          connection.close();
          System.out.println(response.getContentDescription());
        } catch (Exception ex) {
          ex.printStackTrace();
        }

Giving me this response (In wireshark)

<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"                    
    s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
    <s:Body>
        <u:GetBinaryStateResponse xmlns:u="urn:Belkin:service:basicevent:1">
            <BinaryState>0</BinaryState>
        </u:GetBinaryStateResponse>
    </s:Body>
</s:Envelope>

I want to get the BinaryState value (0) or (1) in Java. I'm having a hard time trying to figure out where this is located in the SOAPMessage response. Help would be great. Or even if I could put the XML response in a string and parse it myself.


Solution

  • To turn a SOAPMessage into a String, where you have

    SOAPMessage response = connection.call(sm, endpoint);
    

    Do this:

    SOAPMessage response = connection.call(sm, endpoint);
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    response.writeTo(os);
    String responseXml = new String(os.toByteArray());
    // work with responseXml here...
    

    Edit:

    As an alternative, if all you want is a specific value of an element you already know the name (and that at least one will exist), you may get it trough something like this:

    String responseBinaryState = response.getSOAPBody()
                                         .getElementsByTagName("BinaryState")
                                         .item(0).getTextContent();
    System.out.println("BinaryState: "+responseBinaryState);