Search code examples
javahttpweb-serviceshttp-status-code-401dynamics-business-central

How can I consume web service from business central (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);

Solution

  • 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