Friday, 12 October 2018

Java + SOAP API

<dependency>
<groupId>javax.xml.soap</groupId>
<artifactId>javax.xml.soap-api</artifactId>
<version>1.3.8</version>
</dependency>


package com.google.soap;

import java.io.ByteArrayInputStream;
import java.io.StringWriter;
import java.nio.charset.Charset;
import java.util.Base64;

import javax.xml.soap.MessageFactory;
import javax.xml.soap.MimeHeaders;
import javax.xml.soap.SOAPConnection;
import javax.xml.soap.SOAPConnectionFactory;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPMessage;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

public class Final {
public static void main(String[] args) throws SOAPException {
String str = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/ </soapenv:Body></soapenv:Envelope>";
SOAPConnection connection = null;
String authorization = Base64.getEncoder()
.encodeToString(("uname" + ":" + "pwd").getBytes(Charset.forName("UTF-8")));
String endPointURLString = "http://googlec.om/abc";

try {
SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
connection = soapConnectionFactory.createConnection();
MessageFactory factory = MessageFactory.newInstance();

SOAPMessage request = factory.createMessage(new MimeHeaders(), new ByteArrayInputStream(str.getBytes()));

MimeHeaders headers = request.getMimeHeaders();
headers.addHeader("Authorization", "Basic " + authorization);
headers.addHeader("SOAPAction", "getSum");
headers.addHeader("Content-Type", "multipart/related; type=\"text/xml\";");
request.saveChanges();
SOAPMessage response = connection.call(request, endPointURLString);
System.out.println(getResspString(response));

} catch (Exception ex) {
System.out.println(ex.getMessage());
} finally {
connection.close();
}
}

public static String getResspString(SOAPMessage response) {
final StringWriter sw = new StringWriter();
try {
TransformerFactory.newInstance().newTransformer().transform(new DOMSource(response.getSOAPPart()),
new StreamResult(sw));
} catch (TransformerException e) {
throw new RuntimeException(e);
}
return sw.toString();
}
}

No comments:

Post a Comment