How to prepare SOAP Request and call web service in java - java

I am new to SOAP , I want to call web service .
I have seen a tutorial for making soap request .
This is the Code
MessageFactory mf = null;
SOAPMessage sm = null;
SOAPEnvelope envelope = null;
MimeHeaders headers = null;
SOAPBody body = null;
SOAPElement requestData = null;
SOAPElement requestDoc = null;
CDATASection cdata = null;
SOAPConnectionFactory sfc = null;
SOAPConnection connection = null;
URL requestUrl = null;
SOAPMessage response = null;
OutputStream os = null;
String host = null;
int port = 80;
String path = null;
String api_key = null;
int socket_timeout = 0;
String service_type = null;
String baseXml = null;
try {
xmlChannelRequest = createChannelRequest(cmId, function, guId, password, estabId);
mf = MessageFactory.newInstance();
sm = mf.createMessage();
envelope = sm.getSOAPPart().getEnvelope();
envelope.addNamespaceDeclaration("soap", "http://schemas.xmlsoap.org/soap/envelope/");
envelope.setPrefix("soapenv");
envelope.setAttribute("xmlns:tem", "http://tempuri.org/");
headers = sm.getMimeHeaders();
headers.addHeader("SOAPAction", "http://tempuri.org/IPublicChannelManagerService/RequestData");
body = envelope.getBody();
body.setPrefix("soapenv");
requestData = body.addChildElement("RequestData");
requestData.setPrefix("tem");
requestDoc = requestData.addChildElement("requestDocument", "tem", "http://tempuri.org/");
cdata = requestDoc.getOwnerDocument().createCDATASection("<Request>\n"
+ " <Authentication CMId=\"6438\" Function=\"31\" Guid=\"5594FB83-F4D4-431F-B3C5-EA6D7ASDSBA795\" Password=\"y656g321TR\"/>\n"
+ " <Establishment Id=\"297867\"/>\n"
+ " </Request>");
requestDoc.appendChild(cdata);
System.out.println("---------------- SOAP Request ----------------------------");
sm.writeTo(System.out);
sfc = SOAPConnectionFactory.newInstance();
connection = sfc.createConnection();
requestUrl = new URL("http://pp.xxx.yyyy.co.uk/zzzz.svc?wsdl");
response = connection.call(sm, requestUrl);
This is working fine. My question is , is there any easy way , just like passing object to method and it creates , SOAP request .
ex : Just like JaxB , i will send a Bean , it will generate xml.
outputStream = new ByteArrayOutputStream();
marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(beanObject, outputStream);

You should have the WSDL file before you make the request. Then just generate your specific classes using e.g. wsimport tool and then just call the JAX-WS webservice. You do not have to build the request by yourself in this way.
Have a look over this tutorial.

Related

Capturing Attachment from SOAP response in JAVA

One of my requirement is to send SOAP request, and receive response from Oracle UCM Cloud. I am using Java transformation to do the same. In one of the response, we receive a zip file as attachment, I am not able to capture and download the attachment.
Is there anyway to download the attachment and save to server. The code below captures the whole response into a file, but i want to capture the attachment only.
In Java, I send the below payload
payload = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:typ=\"http://xmlns.oracle.com/apps/financials/commonModules/shared/model/erpIntegrationService/types/\">"+
"<soapenv:Header/>\n"+
"<soapenv:Body>\n"+
"<typ:downloadESSJobExecutionDetails>\n"+
"<typ:requestId>"+i_jobid+"</typ:requestId>\n"+
"<typ:fileType>log</typ:fileType>\n"+
"</typ:downloadESSJobExecutionDetails>\n"+
"</soapenv:Body>\n"+
"</soapenv:Envelope>";
System.out.println(payload);
returnstring=httpPost("https://<<localhost>>.oraclecloud.com/fscmService/ErpIntegrationService?invoke=",payload, "<<credentials>>");
Then i capture the response as :
InputStream in = conn.getInputStream();
InputStreamReader iReader = new InputStreamReader( in );
BufferedReader bReader = new BufferedReader(iReader);
String line;
String response = "";
String fresponse = "";
int lcount = 0;
while ((line = bReader.readLine()) != null)
{
lcount++;
response += line;
}
Then I cut out the xml response part and use only the attachment portion to perform the below tasks
Convert it into bytes and then try and save as zip
byte buf[] = response.getBytes();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ZipOutputStream zos = new ZipOutputStream(baos);
ZipEntry entry = new ZipEntry("abclog.zip");
entry.setSize(buf.length);
zos.putNextEntry(entry);
zos.write(buf);
zos.closeEntry();
zos.close();
java.io.FileOutputStream out_zip_file = new java.io.FileOutputStream("abclogfin.zip");
out_zip_file.write(baos.toByteArray());
The raw response is:
------=_Part_2737_547225473.1557335354007Content-Type: application/xop+xml;charset=UTF-8;
type="text/xml"Content-Transfer-Encoding: 8bitContent-ID: <3196f51c-0526-4921-bde2-d8f8453a255a>
<?xml version="1.0" encoding="UTF-8" ?><env:Envelope xmlns:env="http://schemas.xmlsoap.org/soap/envelope/" xmlns:wsa="http://www.w3.org/2005/08/addressing">
<env:Header><wsa:Action>http://xmlns.oracle.com/apps/financials/commonModules/shared/model/erpIntegrationService//
ErpIntegrationService/downloadESSJobExecutionDetailsResponse</wsa:Action><wsa:MessageID>urn:uuid:db614b6f-cee2-4218-9921-177fa5b71c32</wsa:MessageID>
</env:Header><env:Body><ns0:downloadESSJobExecutionDetailsResponse xmlns:ns0="http://xmlns.oracle.com/apps/financials/commonModules/shared/model/
erpIntegrationService/types/"><ns2:result xmlns:ns2="http://xmlns.oracle.com/apps/financials/commonModules/shared/model/erpIntegrationService/types/"
xmlns:ns1="http://xmlns.oracle.com/adf/svc/types/" xmlns:ns0="http://xmlns.oracle.com/apps/financials/commonModules/shared/model/erpIntegrationService/"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="ns0:DocumentDetails"><ns0:Content><xop:Include xmlns:xop="http://www.w3.org/2004/08/xop/include"
href="cid:8a49811c-492b-4a51-aab2-16abdaf21ad3"/></ns0:Content><ns0:FileName xsi:nil="true"/><ns0:ContentType>zip</ns0:ContentType><ns0:DocumentTitle>ESS_L_13077
</ns0:DocumentTitle><ns0:DocumentAuthor>*****</ns0:DocumentAuthor><ns0:DocumentSecurityGroup>Attachments</ns0:DocumentSecurityGroup><ns0:DocumentAccount xsi:nil="true"/>
<ns0:DocumentName>13077.zip</ns0:DocumentName><ns0:DocumentId xsi:nil="true"/></ns2:result></ns0:downloadESSJobExecutionDetailsResponse></env:Body></env:Envelope>
------=_Part_2737_547225473.1557335354007Content-Transfer-Encoding: binaryContent-ID: <8a49811c-492b-4a51-aab2-16abdaf21ad3>PK
As per my understanding, the values after
<8a49811c-492b-4a51-aab2-16abdaf21ad3>PK
is the attachment, But I am not able to download it. After doing the above process, i get a zip file of 5KB but no contents inside the file.
Ok, SO i got the solution, after a lot of searching around. Posting it here.
Reference:
https://www.programcreek.com/java-api-examples/index.php?api=javax.xml.soap.AttachmentPart
SOlution Code:
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.util.Base64;
import java.util.Iterator;
import javax.xml.soap.*;
public class SOAPClientSAAJ
{
// SAAJ - SOAP Client Testing
public static void main(String args[])
{
String soapEndpointUrl = "https://<<localhost>>.oraclecloud.com/fscmService/ErpIntegrationService";
//This action url will change as per the function you are calling
String soapAction = "http://xmlns.oracle.com/apps/financials/commonModules/shared/model/erpIntegrationService/downloadESSJobExecutionDetails";
String jobid = "13077";
String optype = "log";
String line;
String response = "";
String reqresponse = callSoapWebService(soapEndpointUrl, soapAction, jobid, optype);
if(reqresponse.indexOf("Error")==-1)
{
Reader inputString = new StringReader(reqresponse);
BufferedReader bReader = new BufferedReader(inputString);
int lcount = 0;
try
{
while ((line = bReader.readLine()) != null)
{
lcount++;
if(lcount == 6 || lcount ==7)
{
response += line;
}
}
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println(response);
}
private static void createSoapEnvelope(SOAPMessage soapMessage, String jobid, String optype) throws SOAPException
{
SOAPPart soapPart = soapMessage.getSOAPPart();
//Create this based on the SOAP request XML, you can use SOAP UI to get the XML as you like
String myNamespace = "typ";
String myNamespaceURI = "http://xmlns.oracle.com/apps/financials/commonModules/shared/model/erpIntegrationService/types/";
// SOAP Envelope
SOAPEnvelope envelope = soapPart.getEnvelope();
envelope.addNamespaceDeclaration(myNamespace, myNamespaceURI);
// SOAP Body
SOAPBody soapBody = envelope.getBody();
SOAPElement soapBodyElem = soapBody.addChildElement("downloadESSJobExecutionDetails", myNamespace);
SOAPElement requestId = soapBodyElem.addChildElement("requestId", myNamespace);
requestId.addTextNode(jobid);
SOAPElement fileType = soapBodyElem.addChildElement("fileType", myNamespace);
fileType.addTextNode(optype);
}
private static String callSoapWebService(String soapEndpointUrl, String soapAction, String jobid,String optype)
{
String returnvalue="";
try
{
// Create SOAP Connection
SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
SOAPConnection soapConnection = soapConnectionFactory.createConnection();
// Send SOAP Message to SOAP Server
SOAPMessage soapRequest = createSOAPRequest(soapAction, jobid, optype);
SOAPMessage soapResponse = soapConnection.call(soapRequest, soapEndpointUrl);
// Print the SOAP Response
//System.out.println("Response SOAP Message:");
//soapResponse.writeTo(System.out);
//System.out.println();
/******extract zip****/
try
{
int numOfAttachments = soapResponse.countAttachments();
Iterator<?> attachments = soapResponse.getAttachments();
StringBuilder buf = new StringBuilder("Number of attachments: ");
buf.append(numOfAttachments);
int count = 1;
while (attachments.hasNext())
{
AttachmentPart attachment = (AttachmentPart) attachments.next();
buf.append(" | #").append(count);
buf.append(" | Content Location: ").append(attachment.getContentLocation());
buf.append(" | Content Id: ").append(attachment.getContentId());
buf.append(" | Content Size: ").append(attachment.getSize());
buf.append(" | Content Type: ").append(attachment.getContentType());
buf.append(" | Content String: ").append(attachment.toString());
count++;
//getting the file to particular Driver Name(C drive ,D drive)
//OutputStream fos = new FileOutputStream(new File("D:\\tmp\\fresponse_2048.zip"));
java.io.FileOutputStream out_file = new java.io.FileOutputStream("D:\\tmp\\"+jobid+".zip");
out_file.write(attachment.getRawContentBytes());
out_file.close();
}
//System.out.println(buf.toString());
}
catch (SOAPException e)
{
System.out.println(e.getMessage());
}
/****extract zip*****/
soapConnection.close();
/**write to a variable**/
ByteArrayOutputStream stream = new ByteArrayOutputStream();
soapResponse.writeTo(stream);
returnvalue = new String(stream.toByteArray(), "utf-8");
}
catch (Exception e)
{
returnvalue="Error occurred while sending SOAP Request to Server!\nMake sure you have the correct endpoint URL and SOAPAction!";
}
return returnvalue;
}
private static SOAPMessage createSOAPRequest(String soapAction, String jobid, String optype) throws Exception
{
MessageFactory messageFactory = MessageFactory.newInstance();
SOAPMessage soapMessage = messageFactory.createMessage();
createSoapEnvelope(soapMessage, jobid, optype);
String authstr = "<<userid>>:<<password>>";
byte[] authBytes = authstr.getBytes("UTF-8");
String auth = Base64.getEncoder().encodeToString(authBytes);
//String authorization = new sun.misc.BASE64Encoder().encode((username+":"+password).getBytes());
//MimeHeaders hd = message.getMimeHeaders();
//hd.addHeader("Authorization", "Basic " + authorization);
MimeHeaders headers = soapMessage.getMimeHeaders();
headers.addHeader("Authorization", "Basic " + auth);
headers.addHeader("SOAPAction", soapAction);
soapMessage.saveChanges();
/* Print the request message, just for debugging purposes */
//System.out.println("Request SOAP Message:");
//soapMessage.writeTo(System.out);
//System.out.println("\n");
return soapMessage;
}
}
Adding comments as requested by #Marco
#Marco This is the endpoint url for oracle cloud :
String soapEndpointUrl = "https://<>.oraclecloud.com/fscmService/ErpIntegrationService";
This is the job that will be executed within oracle cloud, this job lets us download the log files
String soapAction = "http://xmlns.oracle.com/apps/financials/commonModules/shared/model/erpIntegrationService/downloadESSJobExecutionDetails";
This specifies which job's log file we are trying to download
String optype="log"
String jobid="123123"
Function createSOAPRequest:
calls createSoapEnvelope function to create a SOAP request XML
used to authenticate using userid/pwd and adding it to the header
Function callSoapWebService:
calls the createSOAPRequest function
then based on the response, tries to download the attachment
Uses javax.xml.soap.* especially the javax.xml.soap.SOAPFactory class to create the SOAP request (https://www.tutorialspoint.com/java/xml/javax_xml_soap_soapfactory.htm),
Uses javax.xml.soap.SOAPConnectionFactor to create a SOAP Connection
SOAPMessage soapRequest = createSOAPRequest(soapAction, jobid, optype); --> creates the soap request
SOAPMessage soapResponse = soapConnection.call(soapRequest, soapEndpointUrl);
--> the o/p of the createSOAPRequest call is passed to soapConnection along with the end point url
--> the o/p of createSOAPRequest is basically the XML request one usually sends in SOAPUI

ServerSOAPFaultException: Client received SOAP Fault from server

I have a wsdl from ERP cloud. To consume it in Java, I compiled it using wsimport and extracted all the java files.
Now I'm trying to use these java files in order to communicate to the server data through wsdl. The wsdl requires authentication.
Problem
Whenever I try to run my custom code to connect to wsdl, for authentication it works with simple setting of username and password in Binding context.
private void attachAuthentication(Object className) {
BindingProvider prov = (BindingProvider) className;
prov.getRequestContext().put(BindingProvider.USERNAME_PROPERTY, "xxx");
prov.getRequestContext().put(BindingProvider.PASSWORD_PROPERTY, "xxx");
}
But whenever I deploy my code on a weblogic GPI instance, it gives me following error.
com.sun.xml.ws.fault.ServerSOAPFaultException: Client received SOAP Fault from server: The request was invalid or malformed Please see the server log to find more detail regarding exact cause of the failure.
at com.sun.xml.ws.fault.SOAP12Fault.getProtocolException(SOAP12Fault.java:229)
at com.sun.xml.ws.fault.SOAPFaultBuilder.createException(SOAPFaultBuilder.java:139)
at com.sun.xml.ws.client.sei.StubHandler.readResponse(StubHandler.java:253)
at com.sun.xml.ws.db.DatabindingImpl.deserializeResponse(DatabindingImpl.java:203)
at com.sun.xml.ws.db.DatabindingImpl.deserializeResponse(DatabindingImpl.java:290)
at com.sun.xml.ws.client.sei.SyncMethodHandler.invoke(SyncMethodHandler.java:119)
I tried attaching a Soap handler to my SEI. Here's what I've done.
InitializeErp.java
HeaderHandlerResolver handlerResolver = new HeaderHandlerResolver();
InvoiceInterfaceService_Service interfaceInvoice = new InvoiceInterfaceService_Service();
interfaceInvoice.setHandlerResolver(handlerResolver);
invoiceInterfaceServiceSoapHttpPort = interfaceInvoice.getInvoiceInterfaceServiceSoapHttpPort();
HeaderHandlerResolver.java
public class HeaderHandlerResolver implements HandlerResolver {
#Override
public List<Handler> getHandlerChain(PortInfo portInfo) {
List<Handler> handlerChain = new ArrayList<Handler>();
HandlerHeader hh = new HandlerHeader();
handlerChain.add(hh);
return handlerChain;
}
}
HeaderHandler.java
public class HandlerHeader implements SOAPHandler<SOAPMessageContext> {
#Override
public Set<QName> getHeaders() {
return Collections.emptySet();
}
#Override
public boolean handleMessage(SOAPMessageContext context) {
final Boolean outInd = (Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
if (outInd) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.mmm'Z'");
Date creationDate = new Date();
Date expirationDate = new Date(creationDate.getTime() + TimeUnit.HOURS.toMillis(1));
try {
SOAPMessage message = context.getMessage();
SOAPEnvelope env = message.getSOAPPart().getEnvelope();
env.addNamespaceDeclaration("sch", "http://xmlns.oracle.com/scheduler");
env.addNamespaceDeclaration("typ", "http://xmlns.oracle.com/scheduler/types");
SOAPHeader header = env.getHeader();
SOAPBody body = env.getBody();
env.removeNamespaceDeclaration("SOAP-ENV");
env.setPrefix("soapenv");
header.setPrefix("soapenv");
body.setPrefix("soapenv");
QName security = new QName("http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd", "Security", "wsse");
// Constructing Header
SOAPElement securityElement = header.addChildElement(security);
securityElement.addNamespaceDeclaration("wsu", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd");
securityElement.setAttribute("soapenv:mustUnderstand", "1");
QName usernameToken = new QName("UsernameToken", "wsse");
SOAPElement usernameTokenElement = securityElement.addChildElement("UsernameToken", "wsse");
usernameTokenElement.setAttribute("wsu:Id", "UsernameToken-97B1FF404874F4997215144527824364");
QName username = new QName("Username", "wsse");
SOAPElement usernameElement = usernameTokenElement.addChildElement("Username", "wsse");
usernameElement.addTextNode("xxx");
QName passwrod = new QName("Password", "wsse");
SOAPElement passwordElement = usernameTokenElement.addChildElement("Password", "wsse");
passwordElement.setAttribute("Type", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText");
passwordElement.addTextNode("xxx");
QName nonce = new QName("Nonce", "wsse");
SOAPElement nonceElement = usernameTokenElement.addChildElement("Nonce", "wsse");
nonceElement.setAttribute("EncodingType", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary");
nonceElement.addTextNode("Ox0BI3sh1pPSe2S7NsUzeg==");
QName created = new QName("Created", "wsu");
SOAPElement createdElement = usernameTokenElement.addChildElement("Created", "wsu");
createdElement.addTextNode(format.format(creationDate));
QName timestamp = new QName("Timestamp", "wsu");
SOAPElement timestampElement = securityElement.addChildElement("Timestamp", "wsu");
timestampElement.setAttribute("wsu:Id", "TS-4");
QName createdTimestamp = new QName("Created", "wsu");
SOAPElement createdTimestampElement = timestampElement.addChildElement("Created", "wsu");
createdTimestampElement.addTextNode(format.format(creationDate));
QName expiresTimestamp = new QName("Expires", "wsu");
SOAPElement expiresTimestampElement = timestampElement.addChildElement("Expires", "wsu");
expiresTimestampElement.addTextNode(format.format(expirationDate));
// Print out the outbound SOAP message to System.out
System.out.println("setting attributes...");
message.writeTo(System.out);
System.out.println("");
System.out.println("message printed..");
} catch (Exception e) {
e.printStackTrace();
}
}
return true;
}
#Override
public boolean handleFault(SOAPMessageContext context) {
try {
SOAPMessage message = context.getMessage();
ByteArrayOutputStream out = new ByteArrayOutputStream();
message.writeTo(out);
String strMsg = new String(out.toByteArray());
RequestFilter.getSession().setAttribute("soap fault", "Soap ->" + strMsg);
} catch (SOAPException | IOException ex) {
RequestFilter.getSession().setAttribute("mailContent", ex.toString());
}
return true;
}
#Override
public void close(MessageContext context) {
}
}
This is what my Soap HEader looks like.
On running it on server. This is what I get in my SoapFault
Soap -> ns1:Senderns2:InvalidRequestThe request was invalid or malformedweblogic.wsee.security.wst.faults.InvalidRequestException: Server Authentication Required at weblogic.wsee.security.wst.framework.TrustSoapClient.invoke(TrustSoapClient.java:157) at weblogic.wsee.security.wst.framework.TrustSoapClient.requestTrustToken(TrustSoapClient.java:110) at weblogic.wsee.security.saml.SAMLTrustCredentialProvider.createCredential(SAMLTrustCredentialProvider.java:432) at
I've many ways to modify the Soap header, Removed security, just passed username password, Added both handler as well as credentials in BindingContext, But nothing seems to work on server.
With the header attached, I get the following error on local
I'm out of ways now. Can anyone please suggest me any approach or point out what am I missing. What should I try now. Any help is appreciated. All suggestions are welcome.

Issue with digitally signed XML inside SOAP message in Java

I have the following Issue:
I'm making an application that sends an already digitally signed XML certificate to an official govt. Webservice.
When I generate the SOAP message, I copy the whole file to a string (I've used several techniques to do this: Guava's File.toString, Files.readAllBytes(Paths.get(path), and tried it with all relevant encodings (UTF-8 and ISO-8859-1, since the document is in spanish). I use logger to store the content of the soap message just before sending it.
The issue is that the webservice gives me an "Invalid signature" answer, but when I copy the soap message from the log, and send it via SoapUI, the webservice accepts the signed certificate.
Here's the code that does the magic:
public class SOAPClientSAAJ {
public static void SendMessage(String file, String rscpath) throws Exception {
// Create SOAP Connection
SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
SOAPConnection soapConnection = soapConnectionFactory.createConnection();
GetCurrentTimeStamp cts = new GetCurrentTimeStamp();
Logger logger = Logger.getLogger("MyLog");
FileHandler fh;
String logfile = rscpath+cts.GetCurrentTimeStamp()+".log";
try {
// This block configure the logger with handler and formatter
fh = new FileHandler(logfile);
logger.addHandler(fh);
SimpleFormatter formatter = new SimpleFormatter();
fh.setFormatter(formatter);
} catch (SecurityException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// Send SOAP Message to SOAP Server
String url = "http://172.25.1.220:8080/SGPRTWebServices/RecepcionCrt";
SOAPMessage soapResponse = null;
SOAPMessage soapmsg = null;
logger.info(file.substring(file.lastIndexOf(File.separator)));
soapmsg = createSOAPRequest(file);
ByteArrayOutputStream out = new ByteArrayOutputStream();
soapmsg.writeTo(out);
String msg = new String(out.toByteArray());
logger.info(msg);
out = null;
msg = null;
try{
soapResponse = soapConnection.call(soapmsg, url);
SOAPPart sp = soapResponse.getSOAPPart();
SOAPEnvelope se = sp.getEnvelope();
SOAPBody sb = se.getBody();
ByteArrayOutputStream out2 = new ByteArrayOutputStream();
soapResponse.writeTo(out2);
msg = new String(out2.toByteArray());
logger.info(msg);
}catch (Exception ex) {
logger.info(ex.toString());
}
soapConnection.close();
}
private static SOAPMessage createSOAPRequest(String confFilePath) throws Exception {
MessageFactory messageFactory = MessageFactory.newInstance();
SOAPMessage soapMessage = messageFactory.createMessage();
SOAPPart soapPart = soapMessage.getSOAPPart();
String serverURI = "http://recepcionCrt.ws.sgprt.mtt.cl/";
Path pat =Paths.get(confFilePath);
Charset charset = StandardCharsets.ISO_8859_1;
String texto = "<![CDATA[";
File fl = pat.toFile();
String content = Files.toString(fl, charset);
texto = texto + content +"]]>";
SOAPEnvelope envelope = soapPart.getEnvelope();
envelope.setEncodingStyle("UTF-8");
SOAPBody soapBody = envelope.getBody();
soapBody.addNamespaceDeclaration("ns2", serverURI);
SOAPElement soapBodyElem = soapBody.addChildElement ("recepcionCRT","ns2");
SOAPElement soapBodyElem1 = soapBodyElem.addChildElement ("arg0");
soapBodyElem1.addTextNode(texto);
MimeHeaders headers = soapMessage.getMimeHeaders();
headers.addHeader("SOAPAction", serverURI + "recepcionCRT");
soapMessage.saveChanges();
return soapMessage;
}
}
Here:can you check some files like the wsdl, a valid certificate and a valid soap message.
As it turned out, the problem was in the communication process. I had to use the importws tool from the jdk to load the interfaces and clases to comunicate with the provider. Once I did that, the message was recieved correctly and the signature verified.

Working Soap client example

I'm trying to find a simple (ha) SOAP example in JAVA with a working service, any I seem to be finding are not working.
I have tried this one from this example but it's just not working, it's asking me to put a forward slash in but it's in there and nothing happening.
So does anyone know any SOAP example links, I can download/request and mess with?
Thanks for your help.
To implement simple SOAP clients in Java, you can use the SAAJ framework (it is shipped with JSE 1.6 and above, but removed again in Java 11):
SOAP with Attachments API for Java (SAAJ) is mainly used for dealing directly with SOAP Request/Response messages which happens behind the scenes in any Web Service API. It allows the developers to directly send and receive soap messages instead of using JAX-WS.
See below a working example (run it!) of a SOAP web service call using SAAJ. It calls this web service.
import javax.xml.soap.*;
public class SOAPClientSAAJ {
// SAAJ - SOAP Client Testing
public static void main(String args[]) {
/*
The example below requests from the Web Service at:
http://www.webservicex.net/uszip.asmx?op=GetInfoByCity
To call other WS, change the parameters below, which are:
- the SOAP Endpoint URL (that is, where the service is responding from)
- the SOAP Action
Also change the contents of the method createSoapEnvelope() in this class. It constructs
the inner part of the SOAP envelope that is actually sent.
*/
String soapEndpointUrl = "http://www.webservicex.net/uszip.asmx";
String soapAction = "http://www.webserviceX.NET/GetInfoByCity";
callSoapWebService(soapEndpointUrl, soapAction);
}
private static void createSoapEnvelope(SOAPMessage soapMessage) throws SOAPException {
SOAPPart soapPart = soapMessage.getSOAPPart();
String myNamespace = "myNamespace";
String myNamespaceURI = "http://www.webserviceX.NET";
// SOAP Envelope
SOAPEnvelope envelope = soapPart.getEnvelope();
envelope.addNamespaceDeclaration(myNamespace, myNamespaceURI);
/*
Constructed SOAP Request Message:
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:myNamespace="http://www.webserviceX.NET">
<SOAP-ENV:Header/>
<SOAP-ENV:Body>
<myNamespace:GetInfoByCity>
<myNamespace:USCity>New York</myNamespace:USCity>
</myNamespace:GetInfoByCity>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
*/
// SOAP Body
SOAPBody soapBody = envelope.getBody();
SOAPElement soapBodyElem = soapBody.addChildElement("GetInfoByCity", myNamespace);
SOAPElement soapBodyElem1 = soapBodyElem.addChildElement("USCity", myNamespace);
soapBodyElem1.addTextNode("New York");
}
private static void callSoapWebService(String soapEndpointUrl, String soapAction) {
try {
// Create SOAP Connection
SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
SOAPConnection soapConnection = soapConnectionFactory.createConnection();
// Send SOAP Message to SOAP Server
SOAPMessage soapResponse = soapConnection.call(createSOAPRequest(soapAction), soapEndpointUrl);
// Print the SOAP Response
System.out.println("Response SOAP Message:");
soapResponse.writeTo(System.out);
System.out.println();
soapConnection.close();
} catch (Exception e) {
System.err.println("\nError occurred while sending SOAP Request to Server!\nMake sure you have the correct endpoint URL and SOAPAction!\n");
e.printStackTrace();
}
}
private static SOAPMessage createSOAPRequest(String soapAction) throws Exception {
MessageFactory messageFactory = MessageFactory.newInstance();
SOAPMessage soapMessage = messageFactory.createMessage();
createSoapEnvelope(soapMessage);
MimeHeaders headers = soapMessage.getMimeHeaders();
headers.addHeader("SOAPAction", soapAction);
soapMessage.saveChanges();
/* Print the request message, just for debugging purposes */
System.out.println("Request SOAP Message:");
soapMessage.writeTo(System.out);
System.out.println("\n");
return soapMessage;
}
}
Yes, if you can acquire any WSDL file, then you can use SoapUI to create mock service of that service complete with unit test requests. I created an example of this (using Maven) that you can try out.
Calculator SOAP service test from SoapUI, Online SoapClient Calculator
Generate the SoapMessage object form the input SoapEnvelopeXML and SoapDataXml.
SoapEnvelopeXML
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
<soapenv:Header/>
<soapenv:Body>
<tem:Add xmlns:tem="http://tempuri.org/">
<tem:intA>3</tem:intA>
<tem:intB>4</tem:intB>
</tem:Add>
</soapenv:Body>
</soapenv:Envelope>
use the following code to get SoapMessage Object.
MessageFactory messageFactory = MessageFactory.newInstance();
MimeHeaders headers = new MimeHeaders();
ByteArrayInputStream xmlByteStream = new ByteArrayInputStream(SoapEnvelopeXML.getBytes());
SOAPMessage soapMsg = messageFactory.createMessage(headers, xmlByteStream);
SoapDataXml
<tem:Add xmlns:tem="http://tempuri.org/">
<tem:intA>3</tem:intA>
<tem:intB>4</tem:intB>
</tem:Add>
use below code to get SoapMessage Object.
public static SOAPMessage getSOAPMessagefromDataXML(String saopBodyXML) throws Exception {
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
dbFactory.setNamespaceAware(true);
dbFactory.setIgnoringComments(true);
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
InputSource ips = new org.xml.sax.InputSource(new StringReader(saopBodyXML));
Document docBody = dBuilder.parse(ips);
System.out.println("Data Document: "+docBody.getDocumentElement());
MessageFactory messageFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL);
SOAPMessage soapMsg = messageFactory.createMessage();
SOAPBody soapBody = soapMsg.getSOAPPart().getEnvelope().getBody();
soapBody.addDocument(docBody);
return soapMsg;
}
By getting the SoapMessage Object. It is clear that the Soap XML is valid. Then prepare to hit the service to get response. It can be done in many ways.
Using Client Code Generated form WSDL.
java.net.URL endpointURL = new java.net.URL(endPointUrl);
javax.xml.rpc.Service service = new org.apache.axis.client.Service();
((org.apache.axis.client.Service) service).setTypeMappingVersion("1.2");
CalculatorSoap12Stub obj_axis = new CalculatorSoap12Stub(endpointURL, service);
int add = obj_axis.add(10, 20);
System.out.println("Response: "+ add);
Using javax.xml.soap.SOAPConnection.
public static void getSOAPConnection(SOAPMessage soapMsg) throws Exception {
System.out.println("===== SOAPConnection =====");
MimeHeaders headers = soapMsg.getMimeHeaders(); // new MimeHeaders();
headers.addHeader("SoapBinding", serverDetails.get("SoapBinding") );
headers.addHeader("MethodName", serverDetails.get("MethodName") );
headers.addHeader("SOAPAction", serverDetails.get("SOAPAction") );
headers.addHeader("Content-Type", serverDetails.get("Content-Type"));
headers.addHeader("Accept-Encoding", serverDetails.get("Accept-Encoding"));
if (soapMsg.saveRequired()) {
soapMsg.saveChanges();
}
SOAPConnectionFactory newInstance = SOAPConnectionFactory.newInstance();
javax.xml.soap.SOAPConnection connection = newInstance.createConnection();
SOAPMessage soapMsgResponse = connection.call(soapMsg, getURL( serverDetails.get("SoapServerURI"), 5*1000 ));
getSOAPXMLasString(soapMsgResponse);
}
Form HTTP Connection Classes org.apache.commons.httpclient.
public static void getHttpConnection(SOAPMessage soapMsg) throws SOAPException, IOException {
System.out.println("===== HttpClient =====");
HttpClient httpClient = new HttpClient();
HttpConnectionManagerParams params = httpClient.getHttpConnectionManager().getParams();
params.setConnectionTimeout(3 * 1000); // Connection timed out
params.setSoTimeout(3 * 1000); // Request timed out
params.setParameter("http.useragent", "Web Service Test Client");
PostMethod methodPost = new PostMethod( serverDetails.get("SoapServerURI") );
methodPost.setRequestBody( getSOAPXMLasString(soapMsg) );
methodPost.setRequestHeader("Content-Type", serverDetails.get("Content-Type") );
methodPost.setRequestHeader("SoapBinding", serverDetails.get("SoapBinding") );
methodPost.setRequestHeader("MethodName", serverDetails.get("MethodName") );
methodPost.setRequestHeader("SOAPAction", serverDetails.get("SOAPAction") );
methodPost.setRequestHeader("Accept-Encoding", serverDetails.get("Accept-Encoding"));
try {
int returnCode = httpClient.executeMethod(methodPost);
if (returnCode == HttpStatus.SC_NOT_IMPLEMENTED) {
System.out.println("The Post method is not implemented by this URI");
methodPost.getResponseBodyAsString();
} else {
BufferedReader br = new BufferedReader(new InputStreamReader(methodPost.getResponseBodyAsStream()));
String readLine;
while (((readLine = br.readLine()) != null)) {
System.out.println(readLine);
}
br.close();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
methodPost.releaseConnection();
}
}
public static void accessResource_AppachePOST(SOAPMessage soapMsg) throws Exception {
System.out.println("===== HttpClientBuilder =====");
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
URIBuilder builder = new URIBuilder( serverDetails.get("SoapServerURI") );
HttpPost methodPost = new HttpPost(builder.build());
RequestConfig config = RequestConfig.custom()
.setConnectTimeout(5 * 1000)
.setConnectionRequestTimeout(5 * 1000)
.setSocketTimeout(5 * 1000)
.build();
methodPost.setConfig(config);
HttpEntity xmlEntity = new StringEntity(getSOAPXMLasString(soapMsg), "utf-8");
methodPost.setEntity(xmlEntity);
methodPost.setHeader("Content-Type", serverDetails.get("Content-Type"));
methodPost.setHeader("SoapBinding", serverDetails.get("SoapBinding") );
methodPost.setHeader("MethodName", serverDetails.get("MethodName") );
methodPost.setHeader("SOAPAction", serverDetails.get("SOAPAction") );
methodPost.setHeader("Accept-Encoding", serverDetails.get("Accept-Encoding"));
// Create a custom response handler
ResponseHandler<String> responseHandler = new ResponseHandler<String>() {
#Override
public String handleResponse( final HttpResponse response) throws ClientProtocolException, IOException {
int status = response.getStatusLine().getStatusCode();
if (status >= 200 && status <= 500) {
HttpEntity entity = response.getEntity();
return entity != null ? EntityUtils.toString(entity) : null;
}
return "";
}
};
String execute = httpClient.execute( methodPost, responseHandler );
System.out.println("AppachePOST : "+execute);
}
Full Example:
public class SOAP_Calculator {
static HashMap<String, String> serverDetails = new HashMap<>();
static {
// Calculator
serverDetails.put("SoapServerURI", "http://www.dneonline.com/calculator.asmx");
serverDetails.put("SoapWSDL", "http://www.dneonline.com/calculator.asmx?wsdl");
serverDetails.put("SoapBinding", "CalculatorSoap"); // <wsdl:binding name="CalculatorSoap12" type="tns:CalculatorSoap">
serverDetails.put("MethodName", "Add"); // <wsdl:operation name="Add">
serverDetails.put("SOAPAction", "http://tempuri.org/Add"); // <soap12:operation soapAction="http://tempuri.org/Add" style="document"/>
serverDetails.put("SoapXML", "<tem:Add xmlns:tem=\"http://tempuri.org/\"><tem:intA>2</tem:intA><tem:intB>4</tem:intB></tem:Add>");
serverDetails.put("Accept-Encoding", "gzip,deflate");
serverDetails.put("Content-Type", "");
}
public static void callSoapService( ) throws Exception {
String xmlData = serverDetails.get("SoapXML");
SOAPMessage soapMsg = getSOAPMessagefromDataXML(xmlData);
System.out.println("Requesting SOAP Message:\n"+ getSOAPXMLasString(soapMsg) +"\n");
SOAPEnvelope envelope = soapMsg.getSOAPPart().getEnvelope();
if (envelope.getElementQName().getNamespaceURI().equals("http://schemas.xmlsoap.org/soap/envelope/")) {
System.out.println("SOAP 1.1 NamespaceURI: http://schemas.xmlsoap.org/soap/envelope/");
serverDetails.put("Content-Type", "text/xml; charset=utf-8");
} else {
System.out.println("SOAP 1.2 NamespaceURI: http://www.w3.org/2003/05/soap-envelope");
serverDetails.put("Content-Type", "application/soap+xml; charset=utf-8");
}
getHttpConnection(soapMsg);
getSOAPConnection(soapMsg);
accessResource_AppachePOST(soapMsg);
}
public static void main(String[] args) throws Exception {
callSoapService();
}
private static URL getURL(String endPointUrl, final int timeOutinSeconds) throws MalformedURLException {
URL endpoint = new URL(null, endPointUrl, new URLStreamHandler() {
protected URLConnection openConnection(URL url) throws IOException {
URL clone = new URL(url.toString());
URLConnection connection = clone.openConnection();
connection.setConnectTimeout(timeOutinSeconds);
connection.setReadTimeout(timeOutinSeconds);
//connection.addRequestProperty("Developer-Mood", "Happy"); // Custom header
return connection;
}
});
return endpoint;
}
public static String getSOAPXMLasString(SOAPMessage soapMsg) throws SOAPException, IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
soapMsg.writeTo(out);
// soapMsg.writeTo(System.out);
String strMsg = new String(out.toByteArray());
System.out.println("Soap XML: "+ strMsg);
return strMsg;
}
}
#See list of some WebServices at http://sofa.uqam.ca/soda/webservices.php
The response of acdcjunior it was awesome, I just expand his explanation with the next code, where you can see how iterate over the XML elements.
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://ws.cdyne.com/emailverify/Emailvernotestemail.asmx";
SOAPMessage soapResponse = soapConnection.call(createSOAPRequest(), url);
SOAPPart soapPart=soapResponse.getSOAPPart();
// SOAP Envelope
SOAPEnvelope envelope=soapPart.getEnvelope();
SOAPBody soapBody = envelope.getBody();
#SuppressWarnings("unchecked")
Iterator<Node> itr=soapBody.getChildElements();
while (itr.hasNext()) {
Node node=(Node)itr.next();
if (node.getNodeType()==Node.ELEMENT_NODE) {
System.out.println("reading Node.ELEMENT_NODE");
Element ele=(Element)node;
System.out.println("Body childs : "+ele.getLocalName());
switch (ele.getNodeName()) {
case "VerifyEmailResponse":
NodeList statusNodeList = ele.getChildNodes();
for(int i=0;i<statusNodeList.getLength();i++){
Element emailResult = (Element) statusNodeList.item(i);
System.out.println("VerifyEmailResponse childs : "+emailResult.getLocalName());
switch (emailResult.getNodeName()) {
case "VerifyEmailResult":
NodeList emailResultList = emailResult.getChildNodes();
for(int j=0;j<emailResultList.getLength();j++){
Element emailResponse = (Element) emailResultList.item(j);
System.out.println("VerifyEmailResult childs : "+emailResponse.getLocalName());
switch (emailResponse.getNodeName()) {
case "ResponseText":
System.out.println(emailResponse.getTextContent());
break;
case "ResponseCode":
System.out.println(emailResponse.getTextContent());
break;
case "LastMailServer":
System.out.println(emailResponse.getTextContent());
break;
case "GoodEmail":
System.out.println(emailResponse.getTextContent());
default:
break;
}
}
break;
default:
break;
}
}
break;
default:
break;
}
} else if (node.getNodeType()==Node.TEXT_NODE) {
System.out.println("reading Node.TEXT_NODE");
//do nothing here most likely, as the response nearly never has mixed content type
//this is just for your reference
}
}
// print SOAP Response
System.out.println("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);
/*
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.println("Request SOAP Message:");
soapMessage.writeTo(System.out);
System.out.println("");
System.out.println("------");
return soapMessage;
}
}
This might help someone who have xml request as string and want to hit soap request from Java like me.
if you have WSDL, You can create a new soap request in SoapUI with that WSDL file.
It would automatically generate the Structure/XML for input request.
Here is some simple version of Java code you can use to call Soap service if you have the input request xml from SoapUI:
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class SimpleSoapClient {
public static void main(String args[]) throws IOException {
String address="Hyderabad";
/* place your xml request from soap ui below with necessary changes in parameters*/
String xml="<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ws=\"http://www.YourUrlAsPerWsdl.com/\">\r\n" +
" <soapenv:Header/>\r\n" +
" <soapenv:Body>\r\n" +
" <ws:callRest>\r\n" +
" <name>"+"Hello"+"</name>\r\n" +
" <address>"+address+"</address>\r\n" +
" </ws:callRest>\r\n" +
" </soapenv:Body>\r\n" +
"</soapenv:Envelope>";
String responseF=callSoapService(xml);
System.out.println(responseF);
}
}
static String callSoapService(String soapRequest) {
try {
String url = "https://gogle.com/service/hello"; // replace your URL here
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// change these values as per soapui request on top left of request, click on RAW, you will find all the headers
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type","text/xml; charset=utf-8");
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(soapRequest);
wr.flush();
wr.close();
String responseStatus = con.getResponseMessage();
System.out.println(responseStatus);
BufferedReader in = new BufferedReader(new InputStreamReader(
con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// You can play with response which is available as string now:
String finalvalue= response.toString();
// or you can parse/substring the required tag from response as below based your response code
finalvalue= finalvalue.substring(finalvalue.indexOf("<response>")+10,finalvalue.indexOf("</response>")); */
return finalvalue;
}
catch (Exception e) {
return e.getMessage();
}
}
}
For Basic Authentication of WSDL the accepted answers code raises an error. Try the following instead
Authenticator.setDefault(new Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("username","password".toCharArray());
}
});
String send =
"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
"<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\">\n" +
" <soap:Body>\n" +
" </soap:Body>\n" +
"</soap:Envelope>";
private static String getResponse(String send) throws Exception {
String url = "https://api.comscore.com/KeyMeasures.asmx"; //endpoint
String result = "";
String username="user_name";
String password="pass_word";
String[] command = {"curl", "-u", username+":"+password ,"-X", "POST", "-H", "Content-Type: text/xml", "-d", send, url};
ProcessBuilder process = new ProcessBuilder(command);
Process p;
try {
p = process.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
StringBuilder builder = new StringBuilder();
String line = null;
while ( (line = reader.readLine()) != null) {
builder.append(line);
builder.append(System.getProperty("line.separator"));
}
result = builder.toString();
}
catch (IOException e)
{ System.out.print("error");
e.printStackTrace();
}
return result;
}

Java SOAP webservice always return null

I have a simple SOAP webservice server like this:
public class receiver extends JAXMServlet implements ReqRespListener {
public SOAPMessage onMessage(SOAPMessage soapm) {
return soapm;
}
}
In the client I send a message to this server:
public class sender {
/** This is a sample web service operation */
SOAPConnectionFactory scfac = null;
SOAPConnection con =null;
MessageFactory fac = null;
SOAPMessage message = null;
SOAPMessage response = null;
#WebMethod(operationName = "sender")
public String sender(#WebParam(name = "a") String a)
{
try{
//Creat Connection
scfac = SOAPConnectionFactory.newInstance();
con = scfac.createConnection();
fac = MessageFactory.newInstance();
message = fac.createMessage();
SOAPPart soapPart = message.getSOAPPart();
SOAPEnvelope envelope = soapPart.getEnvelope();
SOAPHeader header = envelope.getHeader();
header.detachNode();
SOAPBody body = envelope.getBody();
body.addTextNode(a);
URL endpoint = new URL("http://localhost:8080/Target/receiver");
//log("Bat dau gui");
response = con.call(message, endpoint);
//log("Da nhan ve");
SOAPPart sp = response.getSOAPPart();
SOAPEnvelope ev = sp.getEnvelope();
SOAPBody bd = ev.getBody();
String result = bd.getValue();
return result;
}
catch (Exception e)
{
String fail = "Fail to send";
return fail;
}
}
}
I called the sender function in a jsp file and passed a String to it.
I had built it with Netbeans and Tomcat server but it just responds with a null message.
How can I fix the problem?
I had fixed the problem by 2 steps:
The SOAP server: In the web.xml file fix the servlet class from com.sun.xml.ws.transport.http.servlet.WSServlet to your own Java class (in my case it is receive.receiver)
Add saaj-impl-1.3.1 library to NetBeans (the library with method com.sun.xml.messaging)

Categories

Resources