How can I consume web service from business central (Java)? (SOLVED) - java

I want to consume Business Central Web service so I can add it to an existing web application.
I have tried:
Testing with Postman using Authorization header (works)
Testing SoapUI (works)
But I am getting this error:
com.sun.xml.messaging.saaj.client.p2p.HttpSOAPConnection post
SEVERE: SAAJ0008: Bad Response; Unauthorized
Exception in thread "main" com.sun.xml.messaging.saaj.SOAPExceptionImpl: java.security.PrivilegedActionException: com.sun.xml.messaging.saaj.SOAPExceptionImpl: Bad response: (401Unauthorized
at com.sun.xml.messaging.saaj.client.p2p.HttpSOAPConnection.call(HttpSOAPConnection.java:171)
Code:
String webPage = "https://api.businesscentral.dynamics.com/v2.0/<tenant>/...";
String name = "username";
String password = "password";
String authString = name + ":" + password;
String authEncBytes = new String(Base64.getEncoder().encode(authString.getBytes(StandardCharsets.UTF_8)));
String authStringEnc = new String(authEncBytes);
URL url = new URL(webPage);
URLConnection urlConnection = url.openConnection();
urlConnection.setRequestProperty("Authorization", "Basic " + authStringEnc);
MessageFactory messageFactory = MessageFactory.newInstance();
SOAPMessage soapMessage = messageFactory.createMessage();
SOAPPart soapPart = soapMessage.getSOAPPart();
// SOAP Envelope
SOAPEnvelope envelope = soapPart.getEnvelope();
envelope.getHeader().detachNode();
envelope.addHeader();
MimeHeaders hd = soapMessage.getMimeHeaders();
hd.addHeader("Authorization", "Basic " + authEncBytes);
SOAPBody soapBodytxaber = envelope.getBody();
envelope.addNamespaceDeclaration("myNamespace", "uri");
SOAPElement soapBodyElem0txa = soapBodytxaber.addChildElement("Read", "myNamespace");
SOAPElement soapBodyElem1txa = soapBodyElem0txa.addChildElement("No", "myNamespace");
soapBodyElem1txa.addTextNode("00000058");
SOAPConnectionFactory soapConnectionFactory = OAPConnectionFactory.newInstance();
SOAPConnection soapConnection = soapConnectionFactory.createConnection();
soapMessage.saveChanges();
SOAPMessage soapResponse = soapConnection.call(soapMessage, url);

You need to make sure that the user you are trying to authenticate with has a Web Services Access Key.
Then you must use the Web Services Access Key as the password when authenticating.
It does also appear that you are missing a space after Basic in this line of code:
hd.addHeader("Authorization", "Basic" + authEncBytes);
It should probably be
hd.addHeader("Authorization", "Basic " + authEncBytes);

SOLUTION
Okay so after receiving a course, they told me that Basic Authorization is deprecated and they use now OAuth 2...
Thanks for replying
Greetings

Related

How to manually add a cookie to a webservice call in Java?

I want to connect to a webservice (WS). However, a cookie must be provided in order to interact with this webservice.
So far, here is what I have:
String requiredCookieName = "requiredCookieName";
String requiredCookieValue = getRequiredCookieValue();
// Prepare SOAP message
SOAPMessage soapMessage = MessageFactory.newInstance().createMessage();
soapMessage.getMimeHeaders().addHeader("SOAPAction", getSoapAction());
soapMessage.saveChanges();
// Send SOAP message
SOAPConnection soapConnection = buildSoapConnection();
SOAPBody soapBody = soapConnection
// How to add required cookie here before calling WS?
.call(soapMessage, getOperationLocation("operationName"))
.getSOAPBody();
// Process response...
How can I add the required cookie to the underlying HTTP request to WS?
You can do that by adding the corresponding Cookie HTTP header to the message (exactly as you are already doing for the SOAPAction header):
soapMessage.getMimeHeaders().addHeader(
"Cookie", requiredCookieName + "=" + requiredCookieValue);

How to get header elements name and value from SOAP header?

How can I get userID and password tag name and value from soap request Header.
My request xml
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ws="http://WS.com/">
<soapenv:Header>
<userID>34</userID>
<password>test</password>
</soapenv:Header>
<soapenv:Body>
</soapenv:Body>
</soapenv:Envelope>
My java code
MessageFactory messageFactory = MessageFactory.newInstance();
SOAPMessage message = messageFactory.createMessage();
SOAPPart soapPart = message.getSOAPPart();
SOAPEnvelope envelope = soapPart.getEnvelope();
SOAPHeader header = envelope.getHeader();
i want to get userID and password to validate the request.
Please help
Thanks
Try using this code:
// raw SOAP input as String
String input = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ws=\"http://WS.com/\">"
+ "<soapenv:Header>"
+ "<userID>34</userID>"
+ "<password>test</password>"
+ "</soapenv:Header>"
+ "<soapenv:Body>"
+ "</soapenv:Body>"
+ "</soapenv:Envelope>";
// Use MessageFactory with raw input as byte array
InputStream is = new ByteArrayInputStream(input.getBytes());
SOAPMessage message = MessageFactory.newInstance().createMessage(null, is);
SOAPPart soapPart = message.getSOAPPart();
SOAPEnvelope envelope = soapPart.getEnvelope();
SOAPHeader header = envelope.getHeader();
// obtain all Nodes tagged 'userID' or 'password'
NodeList userIdNode = header.getElementsByTagNameNS("*", "userID");
NodeList passwordNode = header.getElementsByTagNameNS("*", "password");
// extract the username and password
String userId = userIdNode.item(0).getChildNodes().item(0).getNodeValue();
String password = passwordNode.item(0).getChildNodes().item(0).getNodeValue();
System.out.println("userID: " + userId);
System.out.println("password: " + password);
Output:
userID: 34
password: test

java.net.MalformedURLException:no protocol

I've the following code
String url = "http://e2e-soaservices:44000/3.1/StandardDocumentService?wsdl";
//createSOAPRequest();
SOAPMessage soapResponse = soapConnection.call(createSOAPRequest(), url);
in the createSOAPRequest Method:-
MessageFactory messageFactory = MessageFactory.newInstance();
SOAPMessage soapMessage = messageFactory.createMessage();
SOAPPart soapPart = soapMessage.getSOAPPart();
File fXmlFile = new File("src/XML/gen_VDD7S0PLYPAS058_1409900400000_2.xml");
String xmlStr=finalXmlString(fXmlFile);
DocumentBuilderFactory docBuilderFactory=DocumentBuilderFactory.newInstance();
docBuilderFactory.setNamespaceAware(true);
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document doc=docBuilder.parse(xmlStr);
System.out.println("dasdasdasd"+doc.toString());
String serverURI = "http://www.aaancnuie.com/DCS/2012/01/DocumentCreation/IStandardDocumentService/CreateDocuments";
// SOAP Envelope
SOAPEnvelope envelope = soapPart.getEnvelope();
envelope.addNamespaceDeclaration("example", serverURI);
SOAPBody soapBody = envelope.getBody();
soapBody.setTextContent(xmlStr);
soapMessage.saveChanges();
return soapMessage;
The error message
Error occurred while sending SOAP Request to Server
java.net.MalformedURLException: no protocol: http%3A%2F%2Fe2e-soaservices%3A44000%2F3.1%2FStandardDocumentService%3Fwsdl
at java.net.URL.<init>(URL.java:567)
at java.net.URL.<init>(URL.java:464)
at java.net.URL.<init>(URL.java:413)
at SOAPCLIENTSAAJ.main(SOAPCLIENTSAAJ.java:36)
You need to encode your URL.
Special character which have to be escaped.
Escaping example:
String url = "http://e2e-soaservices:44000/3.1/StandardDocumentService?wsdl";
String yourURLStr = java.net.URLEncoder.encode(url, "UTF-8");
java.net.URL url = new java.net.URL(yourURLStr);
So, according to the stacktrace that you posted, the actual problem is that you are trying to use a URL where various characters have been %-escaped when they shouldn't be.
http%3A%2F%2Fe2e-soaservices%3A44000%2F3.1%2FStandardDocumentService%3Fwsdl
In particular, the initial http%3A%2F%2F should actually be http://. The URL parser looks for initial : ... and when it can't find it, it complains (correctly!) that there is no protocol component to the URL.
I note that the error message does not match the URL in your code. I don't know what is going on there .... but if the URL in the error message is what is actually being used, then it needs to be decoded (not encoded).
If this is not making sense, please provide a proper complete minimal reproducible example, AND the stack trace that you get from executing that example.

javax web service client array

I'm trying to call a webservice which expects an array as parameter but I've no idea how to do that, I have no wsdl and I'd like to use javax to do that.
String operation = "TheOperationName";
String urn = "TheWebService";
String destination = "http://my-server/something.php";
// First create the connection
SOAPConnectionFactory soapConnFactory = SOAPConnectionFactory.newInstance();
SOAPConnection connection = soapConnFactory.createConnection();
// Next, create the actual message
MessageFactory messageFactory = MessageFactory.newInstance();
SOAPMessage message = messageFactory.createMessage();
SOAPPart soapPart = message.getSOAPPart();
SOAPEnvelope envelope = soapPart.getEnvelope();
envelope.addNamespaceDeclaration("SOAP-ENC", "http://schemas.xmlsoap.org/soap/encoding/");
// Create and populate the body
SOAPBody body = envelope.getBody();
// Create the main element and namespace
SOAPElement operationItem = body.addChildElement(
envelope.createQName(operation, "ns1"));
//Here I'm lost, I should create an array
param0 SOAP-ENC:arrayType="SOAP-ENC:Struct[1]" xsi:type="SOAP-ENC:Array"
which contains my items array
SOAPElement itemElement = myarray.addChildElement("item");
// Add parameters
itemElement.addChildElement("ID_Bug").addTextNode("ID");
itemElement.addChildElement("ID_Release").addTextNode("RELEASE");
// Save the message
message.saveChanges();
// Send the message and get the reply
SOAPMessage reply = connection.call(message, destination);
reply.toString();
// Close the connection
connection.close();
any suggestions on how to achieve that?

Content-Type Missing "start=" Tag in Java SOAP Client, Attachment not Found by Server

I am creating a Java client for a SOAP service that takes an attachment. I'm using java.xml.soap classes, which I have uses before, but not with attachments. The server claims that my attachment is not included.
I used SoapUI, which works, and wireshark to compare my SOAP message to a working SOAP message. One big difference is that my header does not include "start=".
The working Content-Type looks like this:
Content-Type: multipart/related; type="text/xml"; start=""; boundary="----=_Part_23_6341950.1286312374228"
The Content-Type I get from my Java code is like this:
Content-Type: multipart/related; type="text/xml"; boundary="----=_Part_23_6341950.1286312374228"
No start= even when the content ID is set on the root element. The working and failing SOAP messages are otherwise nearly identical. How can I get the start tag generated, or what are other reasons the server might not see the attachment?
Thanks
SOAPMessage soapMessage =
MessageFactory.newInstance().createMessage();
SOAPPart soapPart = soapMessage.getSOAPPart();
SOAPEnvelope soapEnvelope = soapPart.getEnvelope();
SOAPBody body = soapEnvelope.getBody();
SOAPHeader header = soapMessage.getSOAPHeader();
soapPart.setContentId("<rootpart#here.com>");
MimeHeaders mimeHeaders = soapMessage.getMimeHeaders();
mimeHeaders.addHeader("SOAPAction", "addDocument");
mimeHeaders.addHeader("Accept-Encoding", "gzip,deflate");
Name bodyName = soapEnvelope.createName("Document", "doc",
"http://ns/Document");
SOAPBodyElement document = body.addBodyElement(bodyName);
Name filenameName = soapEnvelope.createName("Filename", "doc",
"http://ns/Document");
SOAPElement filename = document.addChildElement(filenameName);
filename.setValue("filename.txt");
AttachmentPart attachment = soapMessage.createAttachmentPart();
attachment.setContent("Some text", "application/octet-stream");
attachment.setMimeHeader("Content-Transfer-Encoding", "binary");
soapMessage.addAttachmentPart(attachment);
SOAPConnectionFactory scf = SOAPConnectionFactory.newInstance();
SOAPConnection soapConnection = scf.createConnection();
URL url = new URL("http://host/Service");
SOAPMessage reply = soapConnection.call(soapMessage, url);
This works for me:
soapMessage.getMimeHeaders().setHeader("Content-Type",
soapMessage.getMimeHeaders().getHeader("Content-Type")[0]+
"; start=\"<rootpart#here.com>\"");

Categories

Resources