Wednesday, November 23, 2011

Java - SOAP Http Post

Use the examples below as a template for posting an xml SOAP message to my document/literal operation style web service. Also, you can customize the message you send to the remote procedure (in bold).
Example 1-11. Upload the SOAP message: PostXml.java
import java.net.*;
import java.io.*;

public class PostXml {

  public static void main(String[] args) {
  
    try {
     /* String xmldata = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + 
 "<env:Envelope " + 
   "env:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\" " + 
   "xmlns:env=\"http://schemas.xmlsoap.org/soap/envelope/\" " + 
   "xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" " + 
   "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">" +
   "<env:Header/>" +
          "<env:Body>" +
     "<ans1:readLS xmlns:ans1=\"http://phonedirlux.homeip.net/types\">" +
       "<String_1 xsi:type=\"xsd:string\">your message or e-mail</String_1>" +
     "</ans1:readLS>" +
   "</env:Body>" +
        "</env:Envelope>"; */
  
     String xmldata = "<s12:Envelope xmlns:s12='http://www.w3.org/2003/05/soap-envelope'>" +
       "<s12:Body> " +
        "<ns1:GetCitiesByCountry xmlns:ns1='http://www.webserviceX.NET'>" +
          "<ns1:CountryName xmlns:ns1='http://www.webserviceX.NET'>Pakistan</ns1:CountryName>" +
        "</ns1:GetCitiesByCountry>" +
      "</s12:Body>" +
      "</s12:Envelope>";
      
      
      //Create socket
      //String hostname = "www.pascalbotte.be";
     String hostname = "www.webservicex.com";
      int port = 80;
      InetAddress  addr = InetAddress.getByName(hostname);
      Socket sock = new Socket(addr, port);
   
      //Send header
      String path = "/rcx-ws/rcx";
      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("POST /globalweather.asmx HTTP/1.1\r\n");      
      //wr.write("Host: www.pascalbotte.be\r\n");
      wr.write("Host: www.webservicex.com\r\n");
      
      
      wr.write("Content-Length: " + xmldata.length() + "\r\n");
      //wr.write("Content-Type: text/xml; charset=\"utf-8\"\r\n");
      wr.write("Content-Type: application/soap+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(line);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}


No comments:

Post a Comment