简体   繁体   中英

How to send SOAP request with username and password like in SOAP UI using java

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?

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() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM