Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

import java.io.IOException;

import java.io.OutputStreamWriter;

import java.io.StringWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.UnknownHostException;

import javax.xml.transform.Result;

import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;

import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Node;

public class Main {
    /**
     * Uses http to post a Document to a URL.
     *
     * @param url
     * @param document
     * @return
     * @throws IOException
     * @throws UnknownHostException
     * @throws TransformerException
     */
    public static HttpURLConnection post(String url, Document document)
            throws IOException, UnknownHostException, TransformerException {
        return post(url, toString(document));
    }

    /**
     * Uses http to post an XML String to a URL.
     *
     * @param url
     * @param xmlString
     * @param return
     * @throws IOException
     * @throws UnknownHostException
     */
    public static HttpURLConnection post(String url, String xmlString) throws IOException, UnknownHostException {

        // open connection
        URL urlObject = new URL(url);
        HttpURLConnection connection = (HttpURLConnection) urlObject.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "text/xml; charset=\"utf-8\"");
        connection.setDoOutput(true);

        OutputStreamWriter outStream = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
        outStream.write(xmlString);
        outStream.close();

        return connection;
    }

    /**
     * Converts an XML node (or document) to an XML String.
     *
     * @param node
     * @return
     * @throws TransformerException
     */
    public static String toString(Node node) throws TransformerException {

        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();

        // Node source
        DOMSource source = new DOMSource(node);

        // StringWriter result
        StringWriter stringWriter = new StringWriter();
        Result result = new StreamResult(stringWriter);

        transformer.transform(source, result);
        return stringWriter.toString();
    }
}