user3236167
user3236167

Reputation:

Consume SOAP web service (having security) in Java

I want to POST the following XML to a web service :-

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:v1="http://<some_site>/retail/schema/inventory/orderlookupservice/v1">
      <soapenv:Header>
            <Security xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" xmlns="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
                  <UsernameToken>
                        <Username>xyzUser</Username>
                        <Password>xyzPass</Password>
                  </UsernameToken>
            </Security>
      </soapenv:Header>
      <soapenv:Body>
            <v1:OrderSearchRequest>
                  <v1:RETAS400OrderNumber>1</v1:RETAS400OrderNumber>
            </v1:OrderSearchRequest>
      </soapenv:Body>
</soapenv:Envelope>

I am expecting the following response XML :-

<?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
      <soapenv:Header/>
      <soapenv:Body>
            <v1:OrderSearchResponse xmlns:v1="http://<some_site>/retail/schema/inventory/orderlookupservice/v1">
                  <v1:error>
                        <v1:errorCode>ERRODR01</v1:errorCode>
                        <v1:errorMessage>Order Number is Invalid</v1:errorMessage>
                  </v1:error>
            </v1:OrderSearchResponse>
      </soapenv:Body>
</soapenv:Envelope>

But instead, I am getting the following response XML indicating some fault :-

<?xml version="1.0" encoding="UTF-8"?>
<env:Envelope xmlns:env="http://schemas.xmlsoap.org/soap/envelope/">
   <env:Header>
   </env:Header>
   <env:Body>
      <env:Fault>
         <faultcode>env:Server
         </faultcode>
         <faultstring>
         </faultstring>
         <detail xmlns:fault="http://www.vordel.com/soapfaults" fault:type="faultDetails">
         </detail>
      </env:Fault>
   </env:Body>
</env:Envelope>

I am using Java 8. I tried to make a POST operation using Apache HTTPClient (version 4.4.1) and SAAJ, in 2 different programs, but unable to fix this one. Can someone please help ?

The SAAJ code is as follows :-

public class RequestInitiation {

    public static void main(String args[]) {

        try {
            // Create SOAP Connection
            SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
            SOAPConnection soapConnection = soapConnectionFactory.createConnection();

            // Send SOAP Message to SOAP Server
            String url = "<service_endpoint>";
            SOAPMessage soapResponse = soapConnection.call(createSOAPRequest(), url);

            // Process the SOAP Response
            printSOAPResponse(soapResponse);

            soapConnection.close();
        } catch (Exception e) {
            System.err.println("Error occurred while sending SOAP Request to Server");
            e.printStackTrace();
        }
    }

    private static SOAPMessage createSOAPRequest() throws Exception {

        MessageFactory messageFactory = MessageFactory.newInstance();
        SOAPMessage soapMessage = messageFactory.createMessage();
        SOAPPart soapPart = soapMessage.getSOAPPart();

        String serverURI = "http://<some_site>/retail/schema/inventory/orderlookupservice/v1";

        SOAPEnvelope envelope = soapPart.getEnvelope();
        envelope.addNamespaceDeclaration("v1", serverURI);

        SOAPHeader header = envelope.getHeader();

        SOAPElement security =
                header.addChildElement("Security", "", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd");
        security.addAttribute(new QName("xmlns:wsu"), "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd");

        SOAPElement usernameToken =
                security.addChildElement("UsernameToken", "");

        SOAPElement username =
                usernameToken.addChildElement("Username", "");
        username.addTextNode("xyzUser");

        SOAPElement password =
                usernameToken.addChildElement("Password", "");
        password.addTextNode("xyzPass");

        SOAPBody soapBody = envelope.getBody();

        SOAPElement soapBodyElem = soapBody.addChildElement("OrderSearchRequest", "v1");
        SOAPElement soapBodyElem1 = soapBodyElem.addChildElement("RETAS400OrderNumber", "v1");
        soapBodyElem1.addTextNode("1");

        soapMessage.setProperty(SOAPMessage.CHARACTER_SET_ENCODING, "UTF-8");

        soapMessage.saveChanges();

        /* Print the request message */
        System.out.print("Request SOAP Message = ");
        soapMessage.writeTo(System.out);
        System.out.println();

        return soapMessage;
    }

    private static void printSOAPResponse(SOAPMessage soapResponse) throws Exception {
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        Source sourceContent = soapResponse.getSOAPPart().getContent();
        System.out.print("\nResponse SOAP Message = ");
        StreamResult result = new StreamResult(System.out);
        transformer.transform(sourceContent, result);
    }
}

The HTTPClient code is as follows :-

public class PostSOAPRequest {

    public static String post() throws Exception {

        HttpClient client = HttpClientBuilder.create().build();
        HttpPost post = new HttpPost("<service_endpoint>");
        String xml = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:v1=\"http://<some_site>/retail/schema/inventory/orderlookupservice/v1\"><soapenv:Header><Security xmlns:wsu=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\" xmlns=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\"><UsernameToken><Username>xyzUser</Username><Password>xyzPass</Password></UsernameToken></Security></soapenv:Header><soapenv:Body><v1:OrderSearchRequest><v1:RETAS400OrderNumber>1</v1:RETAS400OrderNumber></v1:OrderSearchRequest></soapenv:Body></soapenv:Envelope>";
        HttpEntity entity = new ByteArrayEntity(xml.getBytes("UTF-8"));
        post.setEntity(entity);
        HttpResponse response = client.execute(post);
        String result = EntityUtils.toString(response.getEntity());
        return result;
    }

    public static void main(String[] args) {
        try {
            System.out.println(post()); 
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

NOTE : Site name, endpoint, username and password are replaced by dummy values in this message.

Upvotes: 1

Views: 1571

Answers (3)

user6276653
user6276653

Reputation: 140

There are 2 levels of operations that happen : 1. Apply credentials 2. Send message. This 2 step mechanism is available in SAAJ.

Upvotes: 1

Dario Castro
Dario Castro

Reputation: 21

I had exactly the same problem, but on another platform integration. The problem was solved by checking the SOAP Action of the WSDL XML Web service that was consuming, copy and paste the correct SOAP Action in my code and it worked.

Regards.

Upvotes: 0

James Black
James Black

Reputation: 41858

Without being able to see the server side I don't see how to help.

SOAP-ENV:Server There was a problem with the server, so the message could not proceed.

You will need to look at the server logs to determine what is going on, unfortunately.

Upvotes: 1

Related Questions