Tuesday, October 11, 2011

simple way to call a webserivce using HTTP URL Connection



Procedure :

Below is the method for calling werbservice :
Note : here we need to pass wsdl file and also soap request with required parameters

then we have to parse the soap response with xml parsers in our customized way ..




 public static String httpcallWebService() {
        String strXml = "";
        String output = "";
     
        String result = null;
        try {

            webserviceUrl = "http://localhost:8080/WSTest/HelloWorld?wsdl";
            String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?> <soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/' xmlns:com='http://com.in/'><soapenv:Header/><soapenv:Body><com:sayHello><arg0>_name_</arg0></com:sayHello></soapenv:Body></soapenv:Envelope>";
            String xmldata = xml.replaceAll("_name_", "Haasini");

            xmldata = xmldata.trim();
            URL objURL = new URL(webserviceUrl);
            HttpURLConnection objCon = (HttpURLConnection) objURL.openConnection();
            objCon.setRequestMethod("POST");
            objCon.setRequestProperty("SOAPAction", "");
            objCon.setRequestProperty("Content-Type", "text/xml");
            objCon.setDoOutput(true);
            objCon.getOutputStream().write(xmldata.getBytes());
            InputStream ins = objCon.getInputStream();
            byte[] b = new byte[1024 * 4];

            int nBytes = 0;
            while ((nBytes = ins.read(b)) > 0) {
                output += new String(b, 0, nBytes);
            }
            System.out.println("..... Webservice Response ....... ");
            System.out.println("WebResp"+output);

            ByteArrayInputStream bin = new ByteArrayInputStream(output.getBytes());
            Hashtable table = XMLUtil.getXML(bin);
            String strXactionId = (String) table.get("/S:Envelope/S:Body/ns2:sayHelloResponse/return");
            System.out.println("xactionId : " + strXactionId);

            if (output.contains("<return>")) {
                int start = output.indexOf("<return>");
                int end = output.indexOf("</return>");
                start = start + 8;
                result = output.substring(start, end);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        return result;
    }


Another Class ;

public class XMLUtil {

    public static void main(String[] arg){
        try {
            FileInputStream fin = new FileInputStream(arg[0]);
            Hashtable h = XMLUtil.getXML(fin);
            java.util.Enumeration en = h.keys();
            while( en.hasMoreElements()){
                String str = (String)en.nextElement();
                System.out.println(str + " = " + (String)h.get(str));
            }
            fin.close();
        }catch(Exception ex){
            ex.printStackTrace();
        }

    }

    public static StringBuffer addXMLTag(StringBuffer buf,String strName,String strVal,String strDefValue){
        buf.append("<" + strName +">");
        if( ( strVal == null || strVal.length() == 0)){
            buf.append( htmlEncode(strDefValue) );
        }else{
            buf.append( htmlEncode(strVal));
        }
        buf.append("</" + strName +">\r\n");
        return buf;
    }
    public static StringBuffer addXMLTag(StringBuffer buf,String strName,String strVal){
        buf.append("<" + strName +">");
        buf.append(htmlEncode(strVal));
        buf.append("</" + strName +">\r\n");
        return buf;
    }
    public static StringBuffer addXMLTag(StringBuffer buf,String strName,int nVal){
        return addXMLTag(buf,strName,""+nVal);
    }

    public static Hashtable getXML(InputStream inputstream) {
        if(inputstream == null)
            return null;
        try {
            javax.xml.parsers.DocumentBuilderFactory dbf = javax.xml.parsers.DocumentBuilderFactory.newInstance();
            javax.xml.parsers.DocumentBuilder db = dbf.newDocumentBuilder();
            org.w3c.dom.Document d = db.parse(inputstream);
            org.w3c.dom.Element e = d.getDocumentElement();
            org.w3c.dom.NodeList nl = d.getElementsByTagName(e.getTagName());
            Hashtable h = new Hashtable();
            doProcess(nl, h);
            return h;
        }catch(Exception e) {
            System.out.println("Error is : " + e);
            return null;
        }
    }

    static String getName(org.w3c.dom.Node node){
        if( node == null ){
            return null;
        }
        String strName = node.getNodeName();
        org.w3c.dom.Node pNode = node.getParentNode();
        if( pNode != null ){
            return getName(pNode) + "/" + strName.trim();
        }else{
            return "";
        }
    }

    private  static void doProcess(org.w3c.dom.NodeList nl, Hashtable h) {
        int i = 0;
        while(i < nl.getLength()) {
            org.w3c.dom.Node n = nl.item(i);
            String strNodeName = getName(n);
            String strNodeValue = n.getNodeValue();
            if(strNodeName != null)
                strNodeName = strNodeName.trim();

            if(strNodeValue != null)
                strNodeValue = strNodeValue.trim();

            if(strNodeValue != null && strNodeValue.length() != 0) {
                //h.put(n.getParentNode().getNodeName(), strNodeValue);
                h.put(getName(n.getParentNode()), strNodeValue);
            }
            if(n.hasChildNodes())
                doProcess(n.getChildNodes(), h);
            i++;
        }
    }
    public static String htmlDecode(String strMsg){
        strMsg = strMsg.replaceAll("&amp;","&");
        strMsg = strMsg.replaceAll("&lt;","<");
        strMsg = strMsg.replaceAll("&gt;",">");
        strMsg = strMsg.replaceAll("&quot;","\"");
        strMsg = strMsg.replaceAll("&apos;","\'");
        strMsg = strMsg.replaceAll("&nbsp;"," ");
        return strMsg ;
    }
    public static String htmlEncode(String strMsg){
        if( strMsg == null || strMsg.length() == 0 ){
            return strMsg;
        }
        strMsg = strMsg.replaceAll("&","&amp;");
        strMsg = strMsg.replaceAll("<","&lt;");
        strMsg = strMsg.replaceAll(">","&gt;");
        strMsg = strMsg.replaceAll("\"","&quot;");
        strMsg = strMsg.replaceAll("\'","&apos;");
        //strMsg = strMsg.replaceAll("&nbsp;"," ");
        return strMsg ;
    }

}