I have a very strange thing going on.
My code gives me Connection Timeout when I call -> SOAPMessage resp = conn.call(msg, url);
java.net.ConnectException: Connection timed out: connect
So I thought my url for the request or login was wrong but I copy paste the msg from the
LOGGER.info(msg);
and paste it in the Postman and it works, I get the response.
Any idea what might be causing this issue? This seems to be an issue only with the code.
public void updateTicket(String ticketID, String user, String password, String connection, String nameSpace, Map < String, Object > values, Map < String, Object > articleValues, Map < String, Object > dynamicFieldsValues) throws UnsupportedOperationException, SOAPException, IOException, Exception {
// Create the connection
SOAPConnectionFactory scf = SOAPConnectionFactory.newInstance();
SOAPConnection conn = scf.createConnection();
// Create message
MessageFactory mf = MessageFactory.newInstance();
SOAPMessage msg = mf.createMessage();
// Object for message parts
SOAPPart sp = msg.getSOAPPart();
SOAPEnvelope env = sp.getEnvelope();
env.addNamespaceDeclaration("xsd", "http://www.w3.org/2001/XMLSchema");
env.addNamespaceDeclaration("xsi", "http://www.w3.org/2001/XMLSchema-instance");
env.addNamespaceDeclaration("soap", "http://www.w3.org/2003/05/soap-envelope");
env.addNamespaceDeclaration("con", nameSpace);
SOAPBody body = env.getBody();
SOAPElement ticketUpdate = body.addChildElement("TicketUpdate", "con");
ticketUpdate.addChildElement("UserLogin", "con").addTextNode(user);
ticketUpdate.addChildElement("Password", "con").addTextNode(password);
ticketUpdate.addChildElement("TicketID", "con").addTextNode(ticketID);
LOGGER.info("SOAP Request");
LOGGER.info(msg);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
msg.writeTo(stream);
URL url = new URL(connection);
SOAPMessage resp = conn.call(msg, url);
Edit: The connection variable contains the correct SOAP endpoint
Related
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 have a project whereby I have to make a soap request to an endpoint. Using SOAPUI, the request goes quite well and I receive a response, but when I use Java, I receive the following error:
com.sun.xml.internal.messaging.saaj.client.p2p.HttpSOAPConnection post SEVERE: SAAJ0010: Unable to read response
java.lang.NullPointerException
Anyone know why that is so? Here is the part where the call occurs:
InputStream is = new ByteArrayInputStream(message.getBytes("UTF-8"));
MessageFactory factory = MessageFactory.newInstance();
SOAPMessage soapMsg = factory.createMessage(null, is);
SOAPConnectionFactory connFactory = SOAPConnectionFactory.newInstance();
SOAPConnection conn = connFactory.createConnection();
URL endpoint = new URL(Main.SOAP_END_POINT_TESTING);
System.out.println(endpoint);
SOAPMessage response = conn.call(soapMsg, endpoint); //right here is where the error is thrown
The connection is over plain HTTP
Try this :
SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
SOAPConnection soapConnection = soapConnectionFactory.createConnection();
MessageFactory messageFactory = MessageFactory.newInstance();
SOAPMessage soapMessage = messageFactory.createMessage();
SOAPPart soapPart = soapMessage.getSOAPPart();
SOAPEnvelope envelope = soapPart.getEnvelope();
You have to create body here and then save the changes.
soapMessage.saveChanges();
Print the request message
ByteArrayOutputStream outRequest = new ByteArrayOutputStream();
soapMessage.writeTo(outRequest);
String request=outRequest.toString();
SOAPMessage soapResponse = soapConnection.call(soapMessage,url);
i need to communicate with two webservices from my application.
For one webservice i need to use soap1_1 version and for the other soap version is soap1_2. In this case what should be the value set for the system property "javax.xml.soap.MessageFactory"
Client 1:
public class SoapClient1 {
protected static Logger _logger = Logger.getLogger ("TEST");
private static Long retryDelay = null;
public String sendSoapMessage (String xml) throws Exception {
SOAPMessage resp = null;
String response = null;
String endpoint = "http:xxxx";
System.setProperty("javax.xml.soap.MessageFactory","com.sun.xml.internal.messaging.saaj.soap.ver1_2.SOAPMessageFactory1_2Impl");
SOAPConnectionFactory connectionFactory = SOAPConnectionFactory.newInstance();
SOAPConnection soapConnection = connectionFactory.createConnection();
long start = System.currentTimeMillis();
long end = System.currentTimeMillis();
//URL endPoint = new URL(endpoint);
//setting connection time out and read timeout
URL endPoint = new URL (null, endpoint, new URLStreamHandler () {
#Override
protected URLConnection openConnection (URL url) throws IOException {
URL clone = new URL (url.toString ());
URLConnection connection = clone.openConnection ();
connection.setConnectTimeout (60000);
connection.setReadTimeout (60000);
// Custom header
return connection;
}});
try{
start = System.currentTimeMillis();
resp = soapConnection.call(getSoapRequest(xml), endPoint);
end = System.currentTimeMillis();
ByteArrayOutputStream os = new ByteArrayOutputStream();
resp.writeTo(os);
response = os.toString();
if (!resp.getSOAPBody().hasFault()) {
response = "SucCess:" + response;
}else{
response = "FaiLure:" + response;
}
}else{
response = "FaiLure:" + response;
}
}catch(SOAPException se){
_logger.log(Level.ERROR," Service Provisioning Call Failed");
_logger.log(Level.ERROR,"The call duration before SOAPException =" +(end-start)+" ms.");
se.printStackTrace();
throw se;
}
soapConnection.close();
return response;
}
private SOAPMessage getSoapRequest(String xml) throws SOAPException,Exception{
MessageFactory mf = MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL);
/* Create a SOAP message object. */
SOAPMessage soapMessage = mf.createMessage();
SOAPPart soapPart = soapMessage.getSOAPPart();
SOAPEnvelope soapEnvelope = soapPart.getEnvelope();
SOAPBody soapBody = soapEnvelope.getBody();
soapEnvelope.getHeader().detachNode();
soapEnvelope.addNamespaceDeclaration("soap","http://yyyy");
SOAPHeader header = soapEnvelope.addHeader();
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
builderFactory.setNamespaceAware(true);
InputStream stream = new ByteArrayInputStream(xml.getBytes());
Document doc = builderFactory.newDocumentBuilder().parse(stream);
_logger.log(Level.DEBUG, "Adding SOAP Request Body");
soapBody.addDocument(doc);
soapMessage.saveChanges();
return soapMessage;
}
}
sample request
<?xml version="1.0" encoding="UTF-8"?>
<env:Envelope xmlns:env="http://www.w3.org/2003/05/soap-envelope" xmlns:soap="http://bridgewatersystems.com/xpc/tsc/entity/soap">
<env:Header/>
<env:Body>
<TempTierChangeRequest xmlns="http://bridgewatersystems.com/xpc/tsc/entity/soap" credentials="root" principal="root">
<temp-tier-change xmlns="">
<service-components>
<service-component name="DSL_Tier_2"/>
</service-components>
<duration-sec>300</duration-sec>
<description>1024 SC</description>
<activation-date>2017-02-09T10:29:16</activation-date>
<subscriber-id>26752018010#wholesale1.com</subscriber-id>
<partition-key>26752018010</partition-key>
<ttc-id>3706043</ttc-id>
<validity-period>
<duration>30</duration>
<expires-with-billing-reset>1</expires-with-billing-reset>
</validity-period>
</temp-tier-change>
</TempTierChangeRequest>
</env:Body>
</env:Envelope>
It is not possible to set the value of System variable javax.xml.soap.MessageFactory for two different purposes. The default value is set for SOAP 1.1
Remove the system property javax.xml.soap.MessageFactory and depending on the type of client you are building use
Building the soap message with MessageFactory.newInstance()
If you want SOAP1.1, use the default constructor
MessageFactory factory = MessageFactory.newInstance();
If you want SOAP1.2, use
MessageFactory factory = MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL);
See Java Tutorial.
JAX-WS clients configured with annotations #BindingType
#BindingType is used when the JAX-WS client is configured using annotations, for example if client is generated from WSDL. The annotation is added to Port to set the binding to SoapBinding.SOAP11HTTP_BINDING or SoapBinding.SOAP12HTTP_BINDING.
#WebService(targetNamespace = "https://myservice.services.com", name = "myserviceProxyProt")
#BindingType(javax.xml.ws.soap.SOAPBinding.SOAP12HTTP_BINDING)
public interface MyServiceProxyPort {
I have written a Java client code using SAAJ for Primevera P6 webservices. I am getting the below authentication error. I am providing the http username + password to the code but it gives error: SEVERE: SAAJ0008: Bad Response; Unauthorized. Could some one please help me with this issue. I am stuck in this problem since a long time. The wsdl of the web service is: https://sunpower-p6.oracleindustry.com/p6ws-token/services/ProjectService?wsdl.
ERROR:
Request SOAP Message =
11106
Jul 18, 2016 1:03:19 PM com.sun.xml.internal.messaging.saaj.client.p2p.HttpSOAPConnection post
SEVERE: SAAJ0008: Bad Response; Unauthorized
com.sun.xml.internal.messaging.saaj.SOAPExceptionImpl: Bad response: (401Unauthorized
My code:
public class TestClient {
/*
Method used to create the SOAP Request
*/
private static SOAPMessage createSOAPRequest() throws Exception {
// Next, create the actual message
MessageFactory messageFactory = MessageFactory.newInstance();
SOAPMessage soapMessage = messageFactory.createMessage();
SOAPPart soapPart = soapMessage.getSOAPPart();
String serverURI = "http://xmlns.oracle.com/Primavera/P6/WS/Project/V2";
// SOAP Envelope
SOAPEnvelope envelope = soapPart.getEnvelope();
envelope.addNamespaceDeclaration("ProjectService", serverURI);
//start: setting HTTP headers - optional, comment out if not needed
String authorization = Base64Coder.encodeString("xyz:abc");
MimeHeaders hd = soapMessage.getMimeHeaders();
hd.addHeader("Authorization", "Basic " + authorization);
//end: setting HTTP headers
// Create and populate the body
SOAPBody soapBody = envelope.getBody();
// Create the main element and namespace
SOAPElement soapBodyElem = soapBody.addChildElement("ReadProjects", "ProjectService");
SOAPElement soapBodyElem1 = soapBodyElem.addChildElement("Field", "ProjectService");
SOAPElement soapBodyElem2 = soapBodyElem1.addChildElement("Id", "ProjectService");
soapBodyElem2.addTextNode("11106");
hd.addHeader("SOAPAction", serverURI + "ReadProjects");
// Save the message
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 {
// Create the transformer
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
// Extract the content of the reply
Source sourceContent = soapResponse.getSOAPPart().getContent();
// Set the output for the transformation
System.out.println("\nResponse SOAP Message = ");
StreamResult result = new StreamResult(System.out);
transformer.transform(sourceContent, result);
System.out.println();
}
public static void main(String[] args) throws Exception {
try {
// First create the connection
SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
SOAPConnection soapConnection = soapConnectionFactory.createConnection();
//System.out.println(soapConnection);
//Send SOAP Message to SOAP Server
String url = "https://sunpower-p6.oracleindustry.com/p6ws-token/services/ProjectService?wsdl";
// Send the message and get the reply
SOAPMessage soapResponse = soapConnection.call(createSOAPRequest(), url);
// Process the SOAP Response
printSOAPResponse(soapResponse);
soapConnection.close();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
I realize this is an old question but would like to leave some assistance to anyone in the future who ends up here (like I did). There is a few likely situations that I have recently experienced regarding this.
Check that your details are correct, or that the connection is possible. Be 100% sure before moving on.
You will receive an unauthorized error if your database is not correctly configured for some setups (for instance, on JBoss). In my situation the data-source file was not being read properly when it attempted to connect causing the Unauthorized error on the client side.
I am creating a simple soap client payload in java but server replied that "Server didn't recognize the value of http header". I copied the created soap payload and pasted in SOAP-UI and performed the request, the payload works perfectly.
I also double checked soap header information. Everything is correct. But still I am not getting response from my java client.
Can anyone provide me any idea on this?
public class SoapClientClass {
public static void main(String[] args) throws UnsupportedOperationException, SOAPException, IOException, TransformerException {
// TODO Auto-generated method stub
//Getting an instance of Soap Connection factory
SOAPConnectionFactory myFct = SOAPConnectionFactory.newInstance();
//Getting a Soap Connection from the soap connection factory object
SOAPConnection myCon = myFct.createConnection();
//Getting a message factory object to create a message
MessageFactory myMsgFct = MessageFactory.newInstance();
//Using the message factory to create a message
SOAPMessage message = myMsgFct.createMessage();
//Adding message to the body
SOAPPart mySPART = message.getSOAPPart();
SOAPEnvelope myEnvp = mySPART.getEnvelope();
myEnvp.addNamespaceDeclaration("web","http://www.webservicex.net/");
//SOAPHeader header = myEnvp.getHeader();
//javax.xml.soap.Name HeaderName = myEnvp.createName("GetGeoIP", "web","http://www.webservicex.net/");
//SOAPHeaderElement hltp = header.addHeaderElement(HeaderName);
SOAPBody body = myEnvp.getBody();
javax.xml.soap.Name bodyName = myEnvp.createName("GetGeoIP", "web","http://www.webservicex.net/");
SOAPBodyElement gltp = body.addBodyElement(bodyName);
javax.xml.soap.Name myContent = myEnvp.createName("IPAddress","web", "http://www.webservicex.net/");
SOAPElement mySymbol = gltp.addChildElement(myContent);
mySymbol.addTextNode("192.128.62.43");
message.saveChanges();
message.writeTo(System.out);
URLEndpoint endPt = new URLEndpoint("http://www.webservicex.net//geoipservice.asmx");
SOAPMessage reply = myCon.call(message, endPt);
//reply.writeTo(System.out);
System.out.println("\n");
TransformerFactory tff = TransformerFactory.newInstance();
Transformer tf = tff.newTransformer();
Source sc = reply.getSOAPPart().getContent();
StreamResult result = new StreamResult(System.out);
tf.transform(sc, result);
System.out.println("test");
//conn.close();
SOAPBody body1 = reply.getSOAPBody();
if ( body1.hasFault() ) {
SOAPFault newFault = body1.getFault();
QName code = newFault.getFaultCodeAsQName();
String string = newFault.getFaultString();
String actor = newFault.getFaultActor();
System.out.println(string);
}
myCon.close();
//System.out.println(reply);
}
This is very old request but still answering if some one might run into similar issue. As per the error it is expecting HTTP header SOAPAction. Above code required two lines of HTTP header setting code.
SOAPEnvelope myEnvp = mySPART.getEnvelope();
MimeHeaders mheader=message.getMimeHeaders();
mheader.setHeader("SOAPAction", "http://www.webservicex.net/GetGeoIP");
myEnvp.addNamespaceDeclaration("web","http://www.webservicex.net/");