2010/11/22

A Concrete Example for Java HttpURLConnection


import java.io.*;
import java.net.*;

public class Test
{
    public static void main(String[] args) throws Exception
    {
        Test t;
        HttpURLConnection http;

        t = new Test();
        http = t.HttpURLConnection(args[0]);

        http.getOutputStream().flush();
        t.printHttpURL(http);
        http.disconnect();
    }

    public HttpURLConnection HttpURLConnection(String http) throws
            MalformedURLException, IOException
    {
        URL url;
        HttpURLConnection URLConn;

        url = new URL(http);
        URLConn = (HttpURLConnection) url.openConnection();

        URLConn.setDoOutput(true);
        URLConn.connect();

        return URLConn;
    }

    public void printHttpURL(HttpURLConnection url) throws IOException
    {
        BufferedReader in;
        String line;

        in = new BufferedReader(new InputStreamReader(url.getInputStream()));

        while (null != (line = in.readLine()))
            System.out.println(line);

        in.close();
    }
}