SOAP Message Using Sockets

Recently i had to call a webservice for creation of a demo. And i had no time to learn any packages which create SOAP envelope’s. The only thing i know is plan old java. Then i thought why not use sockets for sending messages. Here is a sample Program which sends soap messages and gets response using sockets in Java

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com;

import java.net.*;
import java.io.*;
/**
 *
 * @author Ashwin
 */
public class PostXml {

    public static void main(String[] args) {

        try {
            String xmldata = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><soapenv:Envelope xsi:schemaLocation=\"http://schemas.xmlsoap.org/soap/envelope/ http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd = \"http://www.w3.org/2001/XMLSchema\" xmlns:soapenv = \"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:tab = \"http://j2ee.netbeans.org/xsd/tableSchema\" > <soapenv:Body><tab:PURCHASE_ORDER> <tab:PURCHASE_ORDER_Record><tab:CUSTOMER_ID>1</tab:CUSTOMER_ID><tab:ORDER_NUM>14</tab:ORDER_NUM><tab:QUANTITY>1</tab:QUANTITY><tab:SHIPPING_DATE>2006-07-28</tab:SHIPPING_DATE><tab:FREIGHT_COMPANY>PRimeSOft</tab:FREIGHT_COMPANY><tab:SALES_DATE>2006-07-26</tab:SALES_DATE><tab:SHIPPING_COST>901</tab:SHIPPING_COST><tab:PRODUCT_ID>980001</tab:PRODUCT_ID></tab:PURCHASE_ORDER_Record></tab:PURCHASE_ORDER></soapenv:Body></soapenv:Envelope>";

            //http://localhost:11080/PlaceOrderService/PlaceOrderPort
            //Create socket
            String hostname = "localhost";
            int port = 11080;
            InetAddress addr = InetAddress.getByName(hostname);
            Socket sock = new Socket(addr, port);

            //Send header
            String path = "/PlaceOrderService/PlaceOrderPort";
            BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(sock.getOutputStream(), "UTF-8"));
            // You can use "UTF8" for compatibility with the Microsoft virtual machine.
            wr.write("POST " + path + " HTTP/1.0\r\n");
            wr.write("Host: localhost\r\n");
            wr.write("Content-Length: " + xmldata.length() + "\r\n");
            wr.write("Content-Type: text/xml; charset=\"utf-8\"\r\n");
            wr.write("\r\n");

            //Send data
            wr.write(xmldata);
            wr.flush();

            // Response
            BufferedReader rd = new BufferedReader(new InputStreamReader(sock.getInputStream()));
            String line;
            while ((line = rd.readLine()) != null) {
                System.out.println("Response :"+line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

:- More to Continue On Webservices

Advertisements