Example 6-27: XMLHttp class simplifies posting and getting XML

import java.net.*;
import oracle.xml.parser.v2.*;
import java.io.*;
import org.xml.sax.*;
import java.util.Properties;

public class XMLHttp {
  // POST an XML document to a Service's URL, Returning XML document response
  public static XMLDocument doPost(XMLDocument xmlToPost, URL target)
  throws IOException, ProtocolException {
    // (1) Open an HTTP connection to the target URL
    HttpURLConnection conn = (HttpURLConnection)target.openConnection();
    if (conn == null) return null;
    // (2) Use HTTP POST
    conn.setRequestMethod("POST");
    // (3) Indicate that the content type is XML with appropriate MIME type
    conn.setRequestProperty("Content-type","text/xml");
    // (4) We'll be writing and reading from the connection
    conn.setDoOutput(true);
    conn.setDoInput(true);
    conn.connect();
    // (5) Print the message XML document into the connection's output stream
    xmlToPost.print(new PrintWriter(conn.getOutputStream()));
    // (6) Get an InputStream to read the response from the server.
    InputStream responseStream = conn.getInputStream();
    try {
      // (7) Parse and return the XML document in the server's response
      //     Use the 'target' URL as the base URL for the parsing
      return XMLHelper.parse(responseStream,target);
    }
    catch (Exception e) { return null; }
  }
  // GET an XML document response from a Service's URL request
  public static XMLDocument doGet(URL target) throws IOException {
    try { return XMLHelper.parse(target); }
    catch (SAXException spx) { return null; }
  }
  // Set HTTP proxy server for current Java VM session
  public static void setProxy(String serverName, String port) {
    System.setProperty("proxySet","true");
    System.setProperty("proxyHost",serverName);
    System.setProperty("proxyPort",port);
  }
}