package javakurs.musterloesung.uebung06;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;

/**
 * {@link HtmlContent} is an utility class to fetch content from a web page.
 *
 * @author Ulrich Schaefer, DFKI
 * @version $Id: HtmlContent.java,v 1.1 2010/12/06 18:18:46 steffen Exp $
 */
public final class HtmlContent {

  /**
   * This would create a new instance of {@link HtmlContent}. Not to be used.
   */
  private HtmlContent() {

    // private constructor to enforce noninstantiability
  }


  /**
   * Simple method to get content of a HTTP URL returned as String.
   *
   * @param httpUrl
   *          URL to fetch
   * @param encoding
   *          the encoding to use when reading the URL content
   * @return content of HTML page
   * @throws IOException
   *           if there is a problem when accessing the URL
   */
  public static String getFromUrl(String httpUrl, String encoding)
      throws IOException {

    StringBuilder content = new StringBuilder();
    String newline = System.getProperty("line.separator");
    String lineIn;
    URL url = new URL(httpUrl);
    BufferedReader in =
      new BufferedReader(
        new InputStreamReader(url.openStream(), encoding));
    while ((lineIn = in.readLine()) != null) {
      content.append(lineIn).append(newline);
    }
    in.close();

    return content.toString();
  }
}
