I have a requrement of calling an external webservice from java where I will where I will create the SOAP request and pass to the webservice and will get the SOAP response back ... I went through the following url :- http://www.concretepage.com/webservices/java-saaj-web-service-example to acheive it... My SOAP request is as follow :-
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:v1="http://services.test.com/schema/MainData/V1">
<SOAP-ENV:Header/>
<SOAP-ENV:Body>
<v1:retrieveDataRequest>
<v1:Id>22</v1:Id>
</v1:retrieveDataRequest>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
and my SOAP response is :
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<retrieveDataResponse xmlns="http://services.test.com/schema/MainData/V1">
<Response>The Data retrieved from the Database</Response>
<Id>21</Id>
<Name>fdfdf</Name>
<Age>44</Age>
<Designation>dgdgdfg</Designation>
</retrieveDataResponse>
</soap:Body>
</soap:Envelope>
and my Java code is :-
import javax.xml.soap.*;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
public class Main2
{
/**
* Method used to create the SOAP Request
*/
private static SOAPMessage createSOAPRequest() throws Exception
{
MessageFactory messageFactory = MessageFactory.newInstance();
SOAPMessage soapMessage = messageFactory.createMessage();
SOAPPart soapPart = soapMessage.getSOAPPart();
/*
Construct SOAP Request Message:
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:v1="http://services.test.com/schema/MainData/V1">
<SOAP-ENV:Header/>
<SOAP-ENV:Body>
<v1:retrieveDataRequest>
<v1:Id>21</v1:Id>
</v1:retrieveDataRequest>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
*/
// SOAP Envelope
SOAPEnvelope envelope = soapPart.getEnvelope();
envelope.addNamespaceDeclaration("v1", "http://services.test.com/schema/MainData/V1");
// SOAP Body
SOAPBody soapBody = envelope.getBody();
SOAPElement soapBodyElem = soapBody.addChildElement("retrieveDataRequest", "v1");
SOAPElement soapBodyElem1 = soapBodyElem.addChildElement("Id", "v1");
soapBodyElem1.addTextNode("21");
MimeHeaders headers = soapMessage.getMimeHeaders();
headers.addHeader("SOAPAction", "http://services.test.com/schema/MainData/V1" + "http://services.test.com/schema/MainData/V1/retrieveDataOperation");
soapMessage.saveChanges();
// Check the input
System.out.println("Request SOAP Message = ");
soapMessage.writeTo(System.out);
System.out.println();
return soapMessage;
}
/**
* Method used to print the SOAP Response
*/
private static void printSOAPResponse(SOAPMessage soapResponse) throws Exception
{
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
Source sourceContent = soapResponse.getSOAPPart().getContent();
System.out.println("\nResponse SOAP Message = ");
StreamResult result = new StreamResult(System.out);
transformer.transform(sourceContent, result);
}
/**
* Starting point for the SAAJ - SOAP Client Testing
*/
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 = "http://localhost:8082/mainData?wsdl";
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();
}
}
}
Now my issue is I am getting the SOAP request printed in console but I and not getting the SOAP response back from the service ... Please help ... How to get the SOAP response printed in console ... I am not able to get response
Can you not just try this to capture the response?
SOAPMessage soapResponse = soapConnection.call(createSOAPRequest(), url);
ByteArrayOutputStream out = new ByteArrayOutputStream();
msg.writeTo(out);
String strMsg = new String(out.toByteArray());
Related
I am trying to receive a reply from VIES (a service to validate VAT numbers). I am trying to send SOAP messages, which are shown on their website.
This is the SOAP message they want me to send:
SOAP Request
I tried to do it using these 2 methods:
public static void main(String[] args) {
try {
SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
SOAPConnection soapConnection = soapConnectionFactory.createConnection();
// Send SOAP Message to SOAP Server
String url = "http://ws.cdyne.com/emailverify/Emailvernotestemail.asmx";
SOAPMessage soapResponse = soapConnection.call(createSOAPRequest(), url);
// print SOAP Response
System.out.print("Response SOAP Message:");
soapResponse.writeTo(System.out);
soapConnection.close();
} catch (SOAPException e) {
e.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
}
private static SOAPMessage createSOAPRequest() {
try {
MessageFactory messageFactory = MessageFactory.newInstance();
SOAPMessage soapMessage = messageFactory.createMessage();
SOAPPart soapPart = soapMessage.getSOAPPart();
String serverURI = "urn:ec.europa.eu:taxud:vies:services:checkVat:types";
// SOAP Envelope
SOAPEnvelope envelope = soapPart.getEnvelope();
envelope.addNamespaceDeclaration("urn", serverURI);
/*
Constructed SOAP Request Message:
<soapenv:Envelope xmlns:soapenv=http://schemas.xmlsoap.org/soap/envelope/
xmlns:urn="urn:ec.europa.eu:taxud:vies:services:checkVat:types">
<soapenv:Header/>
<soapenv:Body>
<urn:checkVat>
<urn:countryCode>MS</urn:countryCode>
<urn:vatNumber>TESTVATNUMBER</urn:vatNumber>
</urn:checkVat>
</soapenv:Body>
</soapenv:Envelope>
Constructed SOAP Request Message:
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:example="http://ws.cdyne.com/">
<SOAP-ENV:Header/>
<SOAP-ENV:Body>
<example:VerifyEmail>
<example:email>mutantninja#gmail.com</example:email>
<example:LicenseKey>123</example:LicenseKey>
</example:VerifyEmail>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
*/
// SOAP Body
SOAPBody soapBody = envelope.getBody();
SOAPElement soapBodyElem = soapBody.addChildElement("checkVat", "urn");
SOAPElement soapBodyElem1 = soapBodyElem.addChildElement("countryCode", "urn");
soapBodyElem1.addTextNode("CENSORED");
SOAPElement soapBodyElem2 = soapBodyElem.addChildElement("vatNumber", "urn");
soapBodyElem2.addTextNode("CENSORED");
MimeHeaders headers = soapMessage.getMimeHeaders();
headers.addHeader("SOAPAction", serverURI);
soapMessage.saveChanges();
/* Print the request message */
System.out.print("Request SOAP Message:");
soapMessage.writeTo(System.out);
System.out.println();
return soapMessage;
} catch (SOAPException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
return null;
}
It then gave me this error:
<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body><soap:Fault><faultcode>soap:Client</faultcode><faultstring>Server did not recognize the value of HTTP Header SOAPAction: urn:ec.europa.eu:taxud:vies:services:checkVat:types.</faultstring><detail /></soap:Fault></soap:Body></soap:Envelope>
Any ideas what I could improve to make it working?
Thanks in advance,
Guus Huizen
The code below is what I have been using to understand the concept of soap messages etc. However, in this code there are 2 lines which state-
MimeHeaders headers = soapMessage.getMimeHeaders();
headers.addHeader("SOAPAction", serverURI + "VerifyEmail");
Why is this not viewable when printed? Also I would like to add the header "<?xml version="1.0" encoding="utf-8"?>" How can this be done? and how can I get the entire output/view of what it looks like sent. Header and everything? Thank You.
import javax.xml.soap.*;
import javax.xml.transform.*;
import javax.xml.transform.stream.*;
public class SOAPClientSAAJ {
/**
* Starting point for the SAAJ - SOAP Client Testing
*/
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 = "http://ws.cdyne.com/emailverify/Emailvernotestemail.asmx";
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://ws.cdyne.com/";
// SOAP Envelope
SOAPEnvelope envelope = soapPart.getEnvelope();
envelope.addNamespaceDeclaration("example", serverURI);
/*
Constructed SOAP Request Message:
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:example="http://ws.cdyne.com/">
<SOAP-ENV:Header/>
<SOAP-ENV:Body>
<example:VerifyEmail>
<example:email>mutantninja#gmail.com</example:email>
<example:LicenseKey>123</example:LicenseKey>
</example:VerifyEmail>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
*/
// SOAP Body
SOAPBody soapBody = envelope.getBody();
SOAPElement soapBodyElem = soapBody.addChildElement("VerifyEmail", "example");
SOAPElement soapBodyElem1 = soapBodyElem.addChildElement("email", "example");
soapBodyElem1.addTextNode("mutantninja#gmail.com");
SOAPElement soapBodyElem2 = soapBodyElem.addChildElement("LicenseKey", "example");
soapBodyElem2.addTextNode("123");
MimeHeaders headers = soapMessage.getMimeHeaders();
headers.addHeader("SOAPAction", serverURI + "VerifyEmail");
soapMessage.saveChanges();
/* Print the request message */
System.out.print("Request SOAP Message = ");
soapMessage.writeTo(System.out);
System.out.println();
return soapMessage;
}
/**
* Method used to print the SOAP Response
*/
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);
}
}
I'm not certain whether or not there is a way to print them directly from DOM or SOAP, but you can parse out the values and print them separately:
SOAPHeader header = message.getSOAPHeader();
if (header == null) {
// Throw an exception
}
NodeList headerPartNode = header.getChildNodes();
String headerPart = headerPartNode.item(0).getChildNodes().item(0).getNodeValue();
You can iterate over that NodeList, parse out each header part, and then print them individually for example.
I need to send following soap request on server:
<CallengeState xmlns="http://app.test.com/ws/schema">
<number>0008</number>
<previousState>Stopped</previousState>
<currentState>Activated</currentState>
<dateChanged>2014-06-09</dateChanged>
</CallengeState >
I know how to do it via Soap Ui, but I need to do this via java. In Soap UI I also specify additional parameter, here is screenshot:
I have found in google and tried following:
package com.oberthur.tests.util;
import javax.xml.soap.*;
import javax.xml.transform.*;
import javax.xml.transform.stream.*;
public class SOAPClientSAAJ {
/**
* Starting point for the SAAJ - SOAP Client Testing
*/
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 = "myserver";
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();
// SOAP Envelope
SOAPEnvelope envelope = soapPart.getEnvelope();
SOAPBody soapBody = envelope.getBody();
SOAPElement soapBodyElem = soapBody.addChildElement("CallengeState");
SOAPElement soapBodyElem1 = soapBodyElem.addChildElement("number");
soapBodyElem1.addTextNode("00008");
SOAPElement soapBodyElem2 = soapBodyElem.addChildElement("previousState");
soapBodyElem2.addTextNode("Stoped");
SOAPElement soapBodyElem3 = soapBodyElem.addChildElement("currentState");
soapBodyElem3.addTextNode("Activated");
SOAPElement soapBodyElem4 = soapBodyElem.addChildElement("dateChanged");
soapBodyElem4.addTextNode("2014-06-09");
soapMessage.saveChanges();
/* Print the request message */
System.out.print("Request SOAP Message = ");
soapMessage.writeTo(System.out);
System.out.println();
return soapMessage;
}
/**
* Method used to print the SOAP Response
*/
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);
}
}
But I don't know how to set in this code my parameter and I got following error:
Response SOAP Message = [Fatal Error] :2:6: The processing instruction target matching "[xX][mM][lL]" is not allowed.
Error occurred while sending SOAP Request to Server
I am newbie in SOAP webservice client and getting errors while creating client.
please help me to solve this
//This is request that has to be send using SOAP Envelope
POST /DISWebService/DISWebService.asmx HTTP/1.1
Host: 192.168.2.119
Content-Type: application/soap+xml; charset=utf-8
Content-Length: length
<?xml version="1.0" encoding="utf-8"?>
<soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">
<soap12:Body>
<LoginSystem xmlns="http://tempuri.org/">
<username>string</username>
<password>string</password>
</LoginSystem>
</soap12:Body>
</soap12:Envelope>
Java Code
public static void main(String args[]) {
try {
// Create SOAP Connection
SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory .newInstance();
SOAPConnection soapConnection = soapConnectionFactory
.createConnection();
String url = "http://192.168.2.119/VISWebService/VISWebService.asmx";
// String url =
// "http://192.168.2.119/DISWebService/DISWebService.asmx?op=LoginSystem";
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://192.168.2.119/DISWebService/DISWebService.asmx";
// SOAP Envelope
SOAPEnvelope envelope = soapPart.getEnvelope();
// SOAP Body
SOAPBody soapBody = envelope.getBody();
SOAPElement soapBodyElem = soapBody.addChildElement("LoginSystem");
SOAPElement soapBodyElem1 = soapBodyElem.addChildElement("username");
soapBodyElem1.addTextNode("Chirendu");
SOAPElement soapBodyElem2 = soapBodyElem.addChildElement("password");
soapBodyElem2.addTextNode("verve12*");
MimeHeaders headers = soapMessage.getMimeHeaders();
headers.addHeader("SOAPAction", serverURI );
soapMessage.saveChanges();
/* Print the request message */
System.out.print("Request SOAP Message = ");
soapMessage.writeTo(System.out);
System.out.println();
return soapMessage;
}
Please help me to create client.
I will suggest debugging in 2 steps
1)Use soapUI and check whether your response in coming or not
2)Use the working example i used from mykong
I am provided with the following example request, but I don't know how to actually execute it.
POST /InfoTransit/userservices.asmx HTTP/1.1
Host: 10.0.2.52
Content-Type: text/xml; charset=utf-8
Content-Length: length
SOAPAction: "http://miz.it/infotransit/GetBusStopsList"
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<GetBusStopsList xmlns="http://miz.it/infotransit">
<auth>
<user>..of course, I have this..</user>
<password>..and this..</password>
</auth>
</GetBusStopsList>
</soap:Body>
</soap:Envelope>
I have tried to write a Java client...
import javax.xml.soap.*;
import javax.xml.transform.*;
import javax.xml.transform.stream.*;
public class SOAPClientSAAJ {
/**
* Starting point for the SAAJ - SOAP Client Testing
*/
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 = "http://miz.it/InfoTransit/userservices.asmx";
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://miz.it/infotransit/GetBusStopsList";
// SOAP Envelope
SOAPEnvelope envelope = soapPart.getEnvelope();
// SOAP Body
SOAPBody soapBody = envelope.getBody();
SOAPElement getBusStopsList = soapBody.addChildElement("GetBusStopsList xmlns='http://miz.it/infotransit'");
SOAPElement auth = getBusStopsList.addChildElement("auth");
SOAPElement user = auth.addChildElement("user");
user.addTextNode(" .... ");
SOAPElement password = auth.addChildElement("password");
password.addTextNode(" ... ");
MimeHeaders headers = soapMessage.getMimeHeaders();
headers.addHeader("SOAPAction", serverURI);
headers.addHeader("Content-Type:", "text/xml; charset=uft-8");
soapMessage.saveChanges();
/* Print the request message */
System.out.print("Request SOAP Message = ");
soapMessage.writeTo(System.out);
System.out.println();
return soapMessage;
}
/**
* Method used to print the SOAP Response
*/
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);
}
}
However, I get a connection time-out. Also, the output SOAP message has an envelope that does'nt completely match the envelope of the example request.
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
Is something wrong with the client? Or is it the service provider?
Can you try this in your code:
SOAPElement getBusStopsList = soapBody.addChildElement("GetBusStopsList", "", "http://miz.it/infotransit");
EDIT: The first letter is lower case in getBusStopsList. So, please try GetBusStopsList.
Here is new code:
SOAPElement GetBusStopsList = soapBody.addChildElement("GetBusStopsList", "", "http://miz.it/infotransit");