Simple SOAP Client: Universal Java SOAP Client

Source: Internet
Author: User
Tags exit command line soap soap client web services stock prices


SOAP (Simple Object Access Protocol) is an evolving standard of the world-level consortium developed by IBM, Microsoft, DevelopMentor and userland Software to exchange information on the network. With the growing number of SOAP servers that can be publicly used on the WEB, soap performs HTML pairs of programs that are written in almost any language-even very short programs written in popular simple languages such as Visual Basic, JavaScript, and Perl. What Web browsers do: It provides a simple way for these programs to take advantage of the ever-increasing sources of information available on the World Wide Web.



Like HTML, SOAP provides a set of tags that represent the role of different pieces of information that are used on the Web to use the HTTP Transport protocol (which SMTP can also send since SOAP 1.1). However, SOAP provides you with much greater power than HTML. With soap, your program sends a "SOAP request" to the SOAP server (a short XML document that describes the method to invoke on the remote machine and all parameters to pass to it). The SOAP server attempts to execute the method with those parameters and sends the SOAP response back to the program. The response can be the result of execution, or it can be an appropriate error message. A public SOAP server can be used to provide the requesting client with stock prices, the latest currency exchange rates, FEDEX package tracking information, algebraic expression solutions, and other types of information.



Before SOAP exists, a program that attempts to use this information must first capture the Web page and then "scrape" the HTML to find the appropriate text. A visual redesign of these Web pages (for example, placing the current stock price in the third column in the table instead of the second column) can make these programs useless. The SOAP specification and the brief SOAP request and response patterns it carries provide a framework for networking between client and server, which is the foundation of much more robust information gathering tools.



There are many SOAP clients available for most popular programming languages; For a detailed list, see the SOAP toolkits section on the SOAP::Lite for Perl home page. Most SOAP clients provide class libraries, COM objects, or equivalent objects that are invoked from your own program. Typically, you use these client libraries to follow the following patterns:



The program passes the name of the remote method to invoke and all required parameters.



The library assembles the appropriate XML document for the SOAP request to package this information.



The library passes this XML document to the SOAP server identified by the SOAP endpoint URL, which is similar to pointing the browser to the WEB server address by specifying the server's URL.



After the SOAP server attempts to execute the method, it assembles the SOAP response XML document containing the execution results and sends it back to the SOAP client.



When a SOAP response is received, the client library parse the XML to obtain the result of the method invocation and pass the result to the program that uses the library.



Soapclient4xg



Introduction to Soap (see DeveloperWorks Graham Glass's well-written "Web Services Revolution" column) always discusses the structure of XML for SOAP requests and responses, but the SOAP client I am exposed to is always implicitly XML-assembled and grammar analysis, so I never have to know. As a person using XML, I wanted to execute the XML part myself; I think if SOAP was so simple, I should be able to write a simple SOAP client to read the XML document of the SOAP request, send it to the SOAP endpoint URL specified on the command line, read back the response document and output the response. This will make it a true universal SOAP client because it invokes any method on any SOAP server.



The Soapclient4xg ("SOAP Client for XML Geeks") Java class, shown in Listing 1, performs this task without using any of the dedicated Java soap classes listed on the previously mentioned soap toolkits page. After examining the required SOAP endpoint URL and SOAP XML document filename parameters and optional SOAP operation parameters, read the file, send it to the SOAP server, read back the response, and then output it to the standard exit.



Because the SOAP client sends an XML SOAP request using the HTTP protocol, a large amount of work that is required is the HTTP setting. Java provides a httpurlconnection class that has many "settings" methods to correctly set each HTTP parameter, and can set most parameters with a simple string. An HTTP parameter that requires a little extra code is content-length, so SOAPCLIENT4XG calculates the length of the XML request by placing it in a byte array after reading the XML request, and then checking the length attribute of the byte array.



You can use other HTTP implementations that will set these HTTP parameters on your behalf. The Sun Open source Brazil WEB application framework automatically handles HTTP issues and makes it easier to handle appropriate SOAP errors because (unlike earlier httpurlconnection classes) It is a not-specific script that eases the Mount diagram with a small Java application Generic HTTP classes that work like and other Web resources.



Please refer to Listing 1 for the complete SOAP client.



Listing 1. The Complete SOAP client


/**
* Soapclient4xg. Read the SOAP envelope file passed as the second
* parameter, pass it to the SOAP endpoint passed as the
* Print out the SOAP envelope passed as a response. With help from Michael
* Brennan 03/09/01
*
*
* @author Bob Ducharme
* @version 1.1
* @param soapurl URL of SOAP Endpoint to send request.
* @param xmlfile2send A file with an XML document of the request.
*
* 5/23/01 Revision:soapaction added
*/
Import java.io.*;
Import java.net.*;
public class Soapclient4xg {
public static void Main (string[] args) throws Exception {
if (Args.length < 2) {
System.err.println ("Usage:java soapclient4xg" +
"Http://soapURL Soapenvelopefile.xml" +
"[SOAPAction]");
System.err.println ("SOAPAction is optional.");
System.exit (1);
}
String soapurl = args[0];
String xmlfile2send = args[1];
String soapaction = "";
if (Args.length > 2)
SOAPAction = args[2];

Create the connection where we ' re going to send the file.
URL url = new URL (soapurl);
URLConnection connection = Url.openconnection ();
HttpURLConnection httpconn = (httpurlconnection) connection;
Open the input file. After we copy it to a byte array, we can
How big it's so we can set the HTTP cotent-length
Property. (Complete e-mail below for more on this.)
FileInputStream fin = new FileInputStream (xmlfile2send);
Bytearrayoutputstream bout = new Bytearrayoutputstream ();

Copy the SOAP file to the open connection.
Copy (fin,bout);
Fin.close ();
Byte[] B = Bout.tobytearray ();
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);
Httpconn.setrequestmethod ("POST");
Httpconn.setdooutput (TRUE);
Httpconn.setdoinput (TRUE);
Everything ' s set up; Send the XML that is read in to B.
OutputStream out = Httpconn.getoutputstream ();
Out.write (b);
Out.close ();
Read the response and write it to standard out.
InputStreamReader ISR =
New InputStreamReader (Httpconn.getinputstream ());
BufferedReader in = new BufferedReader (ISR);
String Inputline;
while ((Inputline = In.readline ())!= null)
System.out.println (Inputline);
In.close ();
}
Copy method from E.R. Harold's book "Java I/O"
public static void Copy (InputStream in, outputstream out)
Throws IOException {
Don't allow other threads to read from the
Input or write to the output while copying is
Taking place
Synchronized (in) {
Synchronized (out) {
byte[] buffer = new BYTE[256];
while (true) {
int bytesread = in.read (buffer);
if (bytesread = = 1) break;
Out.write (buffer, 0, bytesread);
}
}
}
}
}




Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.