Ayer publicábamos este post:
Cómo verificar si un Web Service es correcto
Y bien, ¿qué pasa si el Web Service que tengo que invocar no es correcto pero tengo control sobre él?
Pues en ese caso tendremos que prescindir de la librería que usemos (por ejemplo CXF) y de las utilidades que nos da (WSDL2Java, proxys dinámicos) y nos tocará hacer una invocación a mano del WebService:
La opción más usual es usar las liberías javax.xml.soap e invocar como indican en este post
// Create SOAP Connection
SOAPConnectionFactory soapConnectionFactory =SOAPConnectionFactory.newInstance();
SOAPConnection soapConnection =soapConnectionFactory.createConnection();
//Send SOAP Message to SOAP Server
String url ="http://localhost:8080/axis2/services/Student?wsdl";
SOAPMessage soapResponse =soapConnection.call(createSOAPRequest(), url);
Construyendo a mano el mensaje SOAP:
private static SOAPMessage createSOAPRequest() throws Exception
{
MessageFactory messageFactory =MessageFactory.newInstance();
SOAPMessage soapMessage =messageFactory.createMessage();
SOAPPart soapPart = soapMessage.getSOAPPart();
/*
Construct SOAP Request Message:
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope"
xmlns:sam="http://samples.axis2.techdive.in">
<soap:Header/>
<soap:Body>
<sam:getStudentName>
<!–Optional:–>
<sam:rollNumber>3</sam:rollNumber>
</sam:getStudentName>
</soap:Body>
</soap:Envelope>
*/
// SOAP Envelope
SOAPEnvelope envelope = soapPart.getEnvelope();
envelope.addNamespaceDeclaration("sam","http://samples.axis2.techdive.in");
// SOAP Body
SOAPBody soapBody = envelope.getBody();
SOAPElement soapBodyElem =soapBody.addChildElement("getStudentName", "sam");
SOAPElement soapBodyElem1 =soapBodyElem.addChildElement("rollNumber", "sam");
soapBodyElem1.addTextNode("3");
soapMessage.saveChanges();
// Check the input
System.out.println("Request SOAP Message = ");
soapMessage.writeTo(System.out);
System.out.println();
return soapMessage;
}
Os podéis encontrar con que la estructura del mensaje SOAP no puede construirse con el SOAPMessage, en estos casos una simple conexión HTTP puede serviros como en este ejemplo:
String responseString = "";
String outputString = "";
String wsURL = "http://www.deeptraining.com/webservices/weather.asmx";
URL url = new URL(wsURL);
URLConnection connection = url.openConnection();
HttpURLConnection httpConn = (HttpURLConnection)connection;
ByteArrayOutputStream bout = new ByteArrayOutputStream();
String xmlInput =
" <soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:web=\"http://litwinconsulting.com/webservices/\">\n" +
" <soapenv:Header/>\n" +
" <soapenv:Body>\n" +
" <web:GetWeather>\n" +
" <!–Optional:–>\n" +
" <web:City>" + city + "</web:City>\n" +
" </web:GetWeather>\n" +
" </soapenv:Body>\n" +
" </soapenv:Envelope>";
byte[] buffer = new byte[xmlInput.length()];
buffer = xmlInput.getBytes();
bout.write(buffer);
byte[] b = bout.toByteArray();
String SOAPAction =
"http://litwinconsulting.com/webservices/GetWeather";
// Set the appropriate HTTP parameters.
httpConn.setRequestProperty("Content-Length",
String.valueOf(b.length));
httpConn.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
httpConn.setRequestProperty("SOAPAction", SOAPAction);
httpConn.setRequestMethod("POST");
httpConn.setDoOutput(true);
httpConn.setDoInput(true);
OutputStream out = httpConn.getOutputStream();
//Write the content of the request to the outputstream of the HTTP Connection.
out.write(b);
out.close();
//Ready with sending the request.
//Read the response.
InputStreamReader isr =
new InputStreamReader(httpConn.getInputStream());
BufferedReader in = new BufferedReader(isr);
//Write the SOAP message response to a String.
while ((responseString = in.readLine()) != null) {
outputString = outputString + responseString;
}
//Parse the String output to a org.w3c.dom.Document and be able to reach every node with the org.w3c.dom API.
Document document = parseXmlFile(outputString);
NodeList nodeLst = document.getElementsByTagName("GetWeatherResult");
String weatherResult = nodeLst.item(0).getTextContent();
System.out.println("Weather: " + weatherResult);
//Write the SOAP message formatted to the console.
String formattedSOAPResponse = formatXML(outputString);
System.out.println(formattedSOAPResponse);

Deja un comentario