Reputation: 171
Sorry if this question is duplicated, but I tried a couple of solutions in StackOverflow and still get issue with sending SOAP request.
My current situation is my java application needs to send SOAP request to my customer web service, which I did successfully in SOAP UI, with username, password, Authentication type: Preemptive. Please see the picture
Now I want to do this in Java, I've already created the SOAP envelope, without setting password, the response is exactly the same as in SOAP UI using no authentication, it means the java code only needs to add authentication to work. Here is my current Java code:
callSoapWebService(soapEndpointUrl, soapAction);
private static void callSoapWebService(String soapEndpointUrl, String soapAction) {
try {
// Create SOAP Connection
SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
SOAPConnection soapConnection = soapConnectionFactory.createConnection();
// Send SOAP Message to SOAP Server
SOAPMessage soapResponse = soapConnection.call(createSOAPRequest(soapAction), soapEndpointUrl);
// Print the SOAP Response
System.out.println("Response SOAP Message:");
soapResponse.writeTo(System.out);
System.out.println();
soapConnection.close();
} catch (Exception e) {
System.err.println("\nError occurred while sending SOAP Request to Server!\nMake sure you have the correct endpoint URL and SOAPAction!\n");
e.printStackTrace();
}
}
private static SOAPMessage createSOAPRequest(String soapAction) throws Exception {
MessageFactory messageFactory = MessageFactory.newInstance();
SOAPMessage soapMessage = messageFactory.createMessage();
createSoapEnvelope(soapMessage);
MimeHeaders headers = soapMessage.getMimeHeaders();
headers.addHeader("SOAPAction", soapAction);
soapMessage.saveChanges();
return soapMessage;
}
Inside createSoapEnvelope() is code to create SOAP request body, so I guess I have to do something with the header. Anyone can help me to achieve the authentication like what I did in SOAP UI?
Upvotes: 1
Views: 16931
Reputation: 315
You need to send the username and password in Basic format:
String userAndPassword = String.format("%s:%s",username, password);
String basicAuth = new sun.misc.BASE64Encoder().encode(userAndPassword.getBytes());
MimeHeaders mimeHeaders = message.getMimeHeaders();
mimeHeaders.addHeader("Authorization", "Basic " + basicAuth);
If you are using Java 8 use Base64.getEncoder().encodeToString()
instead of new sun.misc.BASE64Encoder()
.
Upvotes: 4