Java SAAJ Basic Authentication

2019-04-08 05:53发布

问题:

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?

回答1:

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);