3 Replies Latest reply: Jan 10, 2013 5:19 PM by vladodias RSS

    calling secured webservice from java

      Hi Experts,
      I am trying to call a secured webservice from java.
      I got the code to call a non secured web service in java.
      What changes do i need to do in this to call a secured webservice.

      Please help me.
      Thank you

      calling unsecured webservice
      package wscall1;

      import java.io.BufferedReader;
      import java.io.ByteArrayOutputStream;
      import java.io.IOException;

      import java.io.InputStream;
      import java.io.InputStreamReader;
      import java.io.OutputStream;

      import java.io.StringBufferInputStream;
      import java.io.StringReader;
      import java.io.StringWriter;
      import java.io.Writer;

      import java.net.HttpURLConnection;
      import java.net.MalformedURLException;
      import java.net.URL;
      import java.net.URLConnection;

      import java.security.Permission;

      import javax.xml.parsers.DocumentBuilderFactory;

      import javax.xml.parsers.DocumentBuilder;

      import javax.xml.parsers.ParserConfigurationException;

      import org.apache.xml.serialize.OutputFormat;

      import org.apache.xml.serialize.XMLSerializer;

      import org.w3c.css.sac.InputSource;
      import org.w3c.dom.Document;
      import org.w3c.dom.NodeList;

      import org.xml.sax.SAXException;

      public class WSCall2 {
      public WSCall2() {

      public static void main(String[] args) {
      try {
      WSCall2 ss = new WSCall2();
      } catch (Exception e) {


      public String getWeather(String city) throws MalformedURLException, IOException {

      //Code to make a webservice HTTP request
      String responseString = "";
      String outputString = "";
      String wsURL = "https://ewm52rdv:25100/Saws/SawsService";
      URL url = new URL(wsURL);
      URLConnection connection = url.openConnection();
      HttpURLConnection httpConn = (HttpURLConnection)connection;
      ByteArrayOutputStream bout = new ByteArrayOutputStream();

      //Permission p= httpConn.getPermission();

      String xmlInput =

      "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ser=\"http://www.ventyx.com/ServiceSuite\">\n" +
      " <soapenv:Header>\n" +
      "     <soapenv:Security>\n" +
      " <soapenv:UsernameToken>\n" +
      " <soapenv:Username>sawsuser</soapenv:Username>\n" +
      " <soapenv:Password>sawsuser1</soapenv:Password>\n" +
      " </soapenv:UsernameToken>\n" +
      " </soapenv:Security>" + "</soapenv:Header>" + " <soapenv:Body>\n" +

      " <ser:GetUser>\n" +
      " <request><![CDATA[<?xml version=\"1.0\" encoding=\"UTF-8\"?> \n" +
                  "                        <GetUser xmlns=\"http://www.ventyx.com/ServiceSuite\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\n" +
                  "                        <UserId>rs24363t</UserId>\n" +
                  "                        </GetUser>]]>\n" +
      " </request>\n" +
      " </ser:GetUser>\n" +
      " </soapenv:Body>\n" +

      byte[] buffer = new byte[xmlInput.length()];
      buffer = xmlInput.getBytes();
      byte[] b = bout.toByteArray();
      String SOAPAction = "GetUser";
      // Set the appropriate HTTP parameters.
      httpConn.setRequestProperty("Content-Length", String.valueOf(b.length));
      httpConn.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
      httpConn.setRequestProperty("SOAPAction", SOAPAction);

      // System.out.println( "opening service for [" + httpConn.getURL() + "]" );

      OutputStream out = httpConn.getOutputStream();
      //Write the content of the request to the outputstream of the HTTP Connection.
      //Ready with sending the request.

      //Read the response.
      InputStreamReader isr = new InputStreamReader(httpConn.getInputStream());
      BufferedReader in = new BufferedReader(isr);

      //Write the SOAP message response to a String.
      while ((responseString = in.readLine()) != null) {
      outputString = outputString + responseString;
      //Parse the String output to a org.w3c.dom.Document and be able to reach every node with the org.w3c.dom API.
      Document document = parseXmlFile(outputString);
      NodeList nodeLst = document.getElementsByTagName("User");
      String weatherResult = nodeLst.item(0).getTextContent();
      System.out.println("Weather: " + weatherResult);

      //Write the SOAP message formatted to the console.
      String formattedSOAPResponse = formatXML(outputString);
      return weatherResult;

      public String formatXML(String unformattedXml) {
      try {
      Document document = parseXmlFile(unformattedXml);
      OutputFormat format = new OutputFormat(document);
      Writer out = new StringWriter();
      XMLSerializer serializer = new XMLSerializer(out, format);
      return out.toString();
      } catch (IOException e) {
      throw new RuntimeException(e);

      private Document parseXmlFile(String in) {
      try {
      DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
      DocumentBuilder db = dbf.newDocumentBuilder();
      InputSource is = new InputSource(new StringReader(in));

      InputStream ins = new StringBufferInputStream(in);
      return db.parse(ins);
      } catch (ParserConfigurationException e) {
      throw new RuntimeException(e);
      } catch (SAXException e) {
      throw new RuntimeException(e);
      } catch (IOException e) {
      throw new RuntimeException(e);
      } catch (Exception e) {
      throw new RuntimeException(e);

      static {
      javax.net.ssl.HttpsURLConnection.setDefaultHostnameVerifier(new javax.net.ssl.HostnameVerifier() {
      public boolean verify(String hostname, javax.net.ssl.SSLSession sslSession) {
      if (hostname.equals("ewm52rdv")) {
      return true;
      return false;
        • 1. Re: calling secured webservice from java
          I suggest you go for some JAX-WS implementation...

          • 2. Re: calling secured webservice from java
            Hi Vlad ,
            Thank you for your quick response.
            What we are trying is we are invoking webservice by passing SOAP request and we will get soap response back.
            Now How we can call a webservice whth authentication details when we are calling a secured webservice.

            • 3. Re: calling secured webservice from java
              Gayaz  wrote:
              What we are trying is we are invoking webservice by passing SOAP request and we will get soap response back.
              I understand what you're trying to do, the problem is with tools you're using it will take a while for you do anything a little away from the trivial... Using string concatenation and URL connection and HTTP post to call webservices is like to use a hand drill... It may work well to go through soft wood, but it will take a lot of effort against a concrete wall...
              JAX-WS and JAXB and annotations will do everything for you in a couple of lines and IMHO you will take longer to figure out how to do everything by hand than to learn those technologies... they are standard java, no need to add any additional jars...
              That's my thought, hope it helps...