Home > Articles > Home & Office Computing > Mac OS X

  • Print
  • + Share This
Like this article? We recommend

Java Class

The next step is to write the Java class that will be used by the application. In this very simple example, I created a single Java class that will be initialized and retained by the AppDelegate. The code for URLRetriever.java is as follows:

import java.net.URL;
import java.net.MalformedURLException;
import java.net.URLConnection;
import java.io.BufferedReader;
import java.io.InputStreamReader;

public class URLRetriever {
   private URL url;

   public URLRetriever() {

   public boolean setURL(String s) {
     try {
       url = new URL(s);
       return true;
     } catch (MalformedURLException e) {
       return false;

   public String retrieveSource() {
     try {
       URLConnection conn = url.openConnection();
       BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
       StringBuffer sb = new StringBuffer();
       for (String s = reader.readLine(); s != null; s = reader.readLine()) {
       return sb.toString();
     } catch (Exception e) {
       return "Error retrieving data";

In this example, a URL is passed in and verified against being malformed. When the retrieveSource method is called, a connection is made to the URL, its contents are retrieved into a StringBuffer, and the results are returned.

  • + Share This
  • 🔖 Save To Your Account