I wrote method, which generate soap message from java string:
private SOAPMessage createRequest(String msg) {
SOAPMessage request = null;
try {
MessageFactory msgFactory = MessageFactory.newInstance();
request = factory.createMessage();
SOAPPart msgPart = request.getSOAPPart();
SOAPEnvelope envelope = msgPart.getEnvelope();
SOAPBody body = envelope.getBody();
StreamSource _msg = new StreamSource(new StringReader(msg));
msgPart.setContent(_msg);
request.saveChanges();
} catch(Exception ex) {
ex.printStackTrace();
}
}
And, after that, I try generate some message. For example:
createRequest("test message");
But here - request.saveChanges(); I catch this exception:
com.sun.xml.internal.messaging.saaj.SOAPExceptionImpl: Error during saving a multipart message
Where is my mistake?
That is because you are not passing a correct protocol formatted message.
Your code doesn't specify which SOAP protocol you want to use, that means it creates a message factory for SOAP 1.1 messages.
Thus, you would need to pass a correct SOAP1.1 message.
I replicated your method like this:
private static SOAPMessage createRequest(String msg) {
SOAPMessage request = null;
try {
MessageFactory msgFactory = MessageFactory
.newInstance(SOAPConstants.SOAP_1_1_PROTOCOL);
request = msgFactory.createMessage();
SOAPPart msgPart = request.getSOAPPart();
SOAPEnvelope envelope = msgPart.getEnvelope();
SOAPBody body = envelope.getBody();
javax.xml.transform.stream.StreamSource _msg = new javax.xml.transform.stream.StreamSource(
new java.io.StringReader(msg));
msgPart.setContent(_msg);
request.saveChanges();
} catch (Exception ex) {
ex.printStackTrace();
}
return request;
}
and I call it using this string:
String soapMessageString = "<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\"><SOAP-ENV:Header/><SOAP-ENV:Body></SOAP-ENV:Body></SOAP-ENV:Envelope>";
createRequest(soapMessageString);
and It works.
Related
I'm trying to send files with soap. but somehow I failed. Help me please gave me the codes below and the error I received.
public void SendTest() {
try {
String filePath = "C:/test/fb344a10-713a-4e45-8810-6a82237947af.zip";
String host = "https://test.efatura.gov.tr/earsiv/services/EArsivWsPort?wsdl";
SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
SOAPConnection connection = soapConnectionFactory.createConnection();
java.net.URL endpoint = new URL(host);
MessageFactory messageFactory = MessageFactory.newInstance();
SOAPMessage message = messageFactory.createMessage();
SOAPPart soapPart = message.getSOAPPart();
SOAPEnvelope soapEnvelope = soapPart.getEnvelope();
soapEnvelope.addNamespaceDeclaration("EArsivWsService", "http://earsiv.vedop3.ggm.gov.org/");
SOAPHeader header = message.getSOAPHeader();
SOAPBody body = message.getSOAPBody();
// QName qNameMethod=new QName("","sendDocumentFile","tns");
// SOAPBodyElement bodyElement = (SOAPBodyElement)
// body.addChildElement(qNameMethod);
SOAPFactory soapFactory = SOAPFactory.newInstance();
Name bodyName = soapFactory.createName("http://earsiv.vedop3.ggm.gov.org/", "tns", "sendDocumentFile");
body.addChildElement(new QName("name","fb344a10-713a-4e45-8810-6a82237947af.zip"));
URL url = new File(filePath).toURI().toURL();
DataHandler dataHandler = new DataHandler(url);
AttachmentPart attachment = message.createAttachmentPart(dataHandler);
// attachment.setContentId("");
message.addAttachmentPart(attachment);
message.saveChanges();
SOAPMessage response = connection.call(message, endpoint);
ByteArrayOutputStream bOutput = new ByteArrayOutputStream(8192);
response.writeTo(bOutput);
String strResponse = bOutput.toString();// TODO use encoding for turkish
System.out.println(strResponse);
} catch (SOAPException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Error response:
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<soap:Fault>
<faultcode xmlns:ns1="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">ns1:InvalidSecurity</faultcode>
<faultstring>An error was discovered processing the <wsse:Security> header</faultstring>
</soap:Fault>
</soap:Body>
</soap:Envelope>
SOAP message should be signed with Wss
I have a Java Soap client that send XML requests with service and method to a remote server but it is anormally slow and can't be used professionnaly.
Is there a way to speed it up or is there a faster way to do Soap requests ?
Thank you for your answers. Here is an extract of my Soap client.
private SOAPMessage makeMessage(String nodeName, String xmlStr, boolean asResponse) throws Exception {
MessageFactory msgFactory = MessageFactory.newInstance();
SOAPMessage message = msgFactory.createMessage();
SOAPPart part = message.getSOAPPart();
SOAPEnvelope envelope = part.getEnvelope();
envelope.addNamespaceDeclaration("xsi", "http://www.w3.org/1999/XMLSchema-instance");
envelope.addNamespaceDeclaration("xsd", "http://www.w3.org/1999/XMLSchema");
SOAPBody body = envelope.getBody();
SOAPElement element = body.addChildElement(envelope.createName("ns1:" + this.method + (asResponse ? "Response" : "")));
element.addAttribute(envelope.createName("xmlns:ns1"), "urn:" + this.service);
element.addAttribute(envelope.createName("ns1"), "http://schemas.xmlsoap.org/soap/encoding");
SOAPElement ele2 = element.addChildElement(envelope.createName(nodeName));
ele2.addAttribute(envelope.createName("xsi:type"), "xsd:string");
ele2.addTextNode(xmlStr);
if (!asResponse) message.saveChanges();
return message;
}
private boolean sendRequest() throws Exception {
try {
SOAPConnectionFactory conFactory = SOAPConnectionFactory.newInstance();
SOAPConnection con = conFactory.createConnection();
URL endpoint = new URL(this.getURI());
SOAPMessage message = this.makeMessage("msgstr", this.request.toString(), false);
SOAPMessage retval = con.call(message, endpoint);
//extraction du XML en String lisible du message SOAP
this.response = extractXML(retval);
} catch (Exception e) {
this.response = e.getMessage();
}
return true;
}
You should enable all the trace/log information of the framework that you are using for the client in order to see where the problem is.
If you are using jax-ws a simple way would be:
System.setProperty("com.sun.xml.ws.transport.http.client.HttpTransportPipe.dump", "true");
System.setProperty("com.sun.xml.internal.ws.transport.http.client.HttpTransportPipe.dump", "true");
System.setProperty("com.sun.xml.ws.transport.http.HttpAdapter.dump", "true");
System.setProperty("com.sun.xml.internal.ws.transport.http.HttpAdapter.dump", "true");
See:
Tracing XML request/responses with JAX-WS
I'm trying to interact with a SOAP service.
I'm able to get the SOAP response and by using Source sourceContent = soapResponse.getSOAPPart().getContent(); and transformer.transform(sourceContent, result); , I'm able to see what the output/response is and displaying it in the console.
But, I need to extract sessionID from the response and send that sessionID in a different SOAP request.
Please suggest me the extraction method, building a new SOAP request
Parsing is what I need to do!!
Below is the code for sending the request to the SOAP service:
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 = "https://WWW.DUMMYURL.COM";
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 serverURN = "urn:DUMMYURL.COM";
String serverNS0 = "http://WWW.DUMMYURL.COM";
// SOAP Envelope
SOAPEnvelope envelope = soapPart.getEnvelope();
envelope.addNamespaceDeclaration("urn", serverURN);
envelope.addNamespaceDeclaration("ns0", serverNS0);
// SOAP Body
SOAPBody soapBody = envelope.getBody();
SOAPElement soapBodyElem1 = soapBody.addChildElement("login","urn");
SOAPElement soapBodyElem2 = soapBodyElem1.addChildElement("username","urn");
#SuppressWarnings("unused")
SOAPElement soapBodyElem3 = soapBodyElem2.addTextNode("USERNAME");
SOAPElement soapBodyElem4 = soapBodyElem1.addChildElement("password","urn");
#SuppressWarnings("unused")
SOAPElement soapBodyElem5 = soapBodyElem4.addTextNode("PASSWORD");
MimeHeaders headers = soapMessage.getMimeHeaders();
headers.addHeader("SOAPAction", "https://WWW.DUMMYURL.COM" + "login");
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();
String source = sourceContent.toString();
System.out.print("\nResponse SOAP Message = ");
// Format it
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
StreamResult result = new StreamResult(System.out);
transformer.transform(sourceContent, result);
System.out.println(transformer.toString());
}
Can someone please suggest me a snippet on how should I save the response I'm getting to a file locally?
Currently in the above code the response is getting displayed in the console.
You can use the writeTo method of the SOAPMessage interface to do the same, for example:
FileOutputStream out = new FileOutputStream("somefile");
soapResponse.writeTo(out);
Vinod.
I am trying to add a XML Declaration for ex: <?xml version="1.0" encoding="utf-8"?> to the top of this soap message. Can anyone assist me on how this can be done?
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();
SOAPHeader header = soapMessage.getSOAPHeader();
You need to set a property to the SOAP message.
soapMessage.setProperty(SOAPMessage.WRITE_XML_DECLARATION, "true")
The above code should do that.
Here is the link to setProperty(String property, Object value) documentation.
soapMessage.setProperty(SOAPMessage.CHARACTER_SET_ENCODING, "UTF-8");
soapMessage.setProperty(SOAPMessage.WRITE_XML_DECLARATION, "true");
I have a working soaprequest in PhP and i'm trying to create a java program that requires the same call, However i am really struggeling to find the way to create the below php code in java, i have found numerus websites explaining soap requests in java but i cant seem to work how how to send the $param_auth array.
Any help would be most appreciated as i've been stuck on this for a while.
Thanks in advance.
$param_auth=array(
'user'=>$username,
'id'=>$userID,
'message'=>$userMessage
);
$soapclient = new soapclient(WebsiteAddress);
$data->_db = $soapclient->call('uploadMessage',$param_auth);
Finally solved my issue (Ive changed Element names etc.), using eclipse shows you the Soap envelope and XML response which i found useful for debugging the envelope).
Hope this helps anyone trying to do similar.
The "UploadMessage" is the "Login" string and the
$param_auth=array(
'user'=>$username,
'id'=>$userID,
'message'=>$userMessage
);
is the Username and Password, (Left out the Message part).
This code sends an Envelope like this the server:-
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:Login="Your URL"><SOAP-ENV:Header/><SOAP-ENV:Body><Login><UserName>YourUserName</UserName><Password>YourPassword</Password></Login></SOAP-ENV:Body></SOAP-ENV:Envelope>
Code To create the above Envelope is below:-
import javax.xml.soap.*;
import javax.xml.transform.*;
import javax.xml.transform.stream.*;
public class SoapCall {
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 = "Your URL";
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 {
String YourUsername = "UserName";
String YourPassword = "Password";
MessageFactory messageFactory = MessageFactory.newInstance();
SOAPMessage soapMessage = messageFactory.createMessage();
SOAPPart soapPart = soapMessage.getSOAPPart();
String serverURI = "Your URL";
// SOAP Envelope
SOAPEnvelope envelope = soapPart.getEnvelope();
envelope.addNamespaceDeclaration("Login", serverURI);
SOAPBody soapBody = envelope.getBody();
SOAPElement soapBodyElem = soapBody.addChildElement("Login");
SOAPElement soapBodyElem2 = soapBodyElem.addChildElement("UserName");
soapBodyElem2.addTextNode(YourUserName);
SOAPElement soapBodyElem3 = soapBodyElem.addChildElement("Password");
soapBodyElem3.addTextNode(YourPassword);
MimeHeaders headers = soapMessage.getMimeHeaders();
headers.addHeader("SOAPAction", serverURI + "Login");
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);
}
}