URLs and URLConnections

Back Up Next

 

URLs and URLConnections
URL
The easiest way to retrieve objects named by URLs.

URLRead.java

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

public class URLRead {
	public static void main(String[] args) {
		try {
			URL url = new URL(args[0]);
			BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()));
			StringBuffer buf = new StringBuffer();

			while (br.ready())
				buf.append(br.readLine() + "\r\n");

			br.close();
			System.out.println(buf.toString() + "\n" + buf.length() + " bytes read");
		} catch (MalformedURLException e) {
			System.out.println("Bad URL");
		} catch (IOException ee) {
			System.out.println("Read Error");
		}
	}
}
URLConnection
When you need to do more than retrieve URL named objects, such as send data to an remote cgi script
HttpURLConnection - special version of URLConnection that only does HTTP connections

Reverse.java

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

public class Reverse {
    public static void main(String[] args) throws Exception {

	if (args.length != 1) {
	    System.err.println("Usage:  java Reverse "
                               + "string_to_reverse");
	    System.exit(1);
	}

	String stringToReverse = URLEncoder.encode(args[0]);

	URL url = new URL("http://java.sun.com/cgi-bin/backwards");
	URLConnection connection = url.openConnection();
	connection.setDoOutput(true);

	PrintWriter out = new PrintWriter(connection.getOutputStream());
	out.println("string=" + stringToReverse);
	out.close();

	BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
	String inputLine;

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

	in.close();
    }
}