Java SAAJ Basic Authentication

Ben picture Ben · Jun 11, 2013 · Viewed 16.9k times · Source

I have a basic SOAP service endpoint, actually SAP ECC, presenting a service. I have tested the service using SOAPUI 4.5, and it works ok using HTTP Auth, preemptive by the looks of things. I see an outbound "Authorization:Basic BASE64" and the service responds appropriately.

I am now trying to roll this into Java. I thought that I would take a SAAJ approach with:

 SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
 SOAPConnection soapConnection = soapConnectionFactory.createConnection();
 String url = "http://SAPSERVER:8006/sap/bc/srt/rfc/sap/z_lookup_generic_prototype/300/z_user/z_user_binding";
 SOAPMessage message = messageFactory.createMessage();
 SOAPMessage response = connection.call(message, url);

But I cannot find a way to add the HTTP authentication in. I believe that SAAJ provides the means to control the SOAP message, but how do I add authentication in? Are there any alternatives worth considering?

Answer

Floww picture Floww · Aug 9, 2013

From this page : https://www.coderanch.com/how-to/java/WebServicesHowTo

SOAPMessage message = ...
String authorization = new sun.misc.BASE64Encoder().encode((username+":"+password).getBytes());
MimeHeaders hd = message.getMimeHeaders();
hd.addHeader("Authorization", "Basic " + authorization);