how sent soap request with parameter to server via java - java

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

Related

Java SAAJ memory leak

I have a developED a REST Api with Java and one of the service needs to make a SOAP call to an endpoint. For this I implemented SAAJ client to create the whole xml message. However each time a call consume extra 1 MB of memory.
import javax.xml.soap.*;import javax.xml.transform.* import javax.xml.transform.stream.*;
public class SOAPClientSAAJ {
public void makeCall() {
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);
// 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);
}}
When a call this SOAP service in my rest object and run piece of memory detector ;
public void restService(){
SOAPClientSAAJ test= new SOAPClientSAAJ();
test.makeCall();
Runtime runtime = Runtime.getRuntime();
runtime.gc();
long memory = runtime.totalMemory() - runtime.freeMemory();
System.out.println("Used memory is bytes: " + memory);
}
It shows each call consume 1 MB memory and at the end the Rest application crush. I debug it many times and saw that SOAPMessage soapResponse = soapConnection.call(createSOAPRequest(), url); this part highly is the cause of the leak but I couldn't find a solution. Any help about that would be great.

Adding content to soap message(basic)

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.

How to add parameters to the SOAP Request

I want to call RFC function in SAP, I already could make request from Java and get the WSDL response. But I want to send a parameter with the SOAP request ? How to do that ?
The class below, I used it to create the request and get response :
public class SOAPClientSAAJ {
public static void main(String args[]) throws Exception {
// Create SOAP Connection
SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
SOAPConnection soapConnection = soapConnectionFactory.createConnection();
// Send SOAP Message to SOAP Server
String url = "http://10.130.105.8:8000/sap/bc/.....client=520";
SOAPMessage soapResponse = soapConnection.call(createSOAPRequest(), url);
// print SOAP Response
System.out.print("Response SOAP Message:");
soapResponse.writeTo(System.out);
soapConnection.close();
}
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);
// SOAP Body
SOAPBody soapBody = envelope.getBody();
SOAPElement soapBodyElem = soapBody.addChildElement("pernr","example");
soapBodyElem.addTextNode("10001001");
String authorization = new String(Base64.encodeBase64(("hr_develop:unrwa2013").getBytes()));
soapMessage.getMimeHeaders().addHeader("Authorization","Basic " + authorization);
soapMessage.saveChanges();
/* Print the request message */
soapMessage.writeTo(System.out);
System.out.println();
return soapMessage;
}
}

Not able to get SOAP response after calling external webservice from java

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());

Web service call with Java using SOAP

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");

Categories

Resources