java web page download


/ Published in: Java
Save to your folder(s)



Copy this code and paste it in your HTML
  1. import java.io.BufferedInputStream;
  2. import java.io.IOException;
  3. import java.net.MalformedURLException;
  4. import java.net.URL;
  5. import java.net.URLConnection;
  6.  
  7. /**
  8.  * Main.java
  9.  *
  10.  * @author www.javadb.com
  11.  */
  12. public class Main {
  13.  
  14. /**
  15.   * Reads a web page into a StringBuilder object
  16.   * and prints it out to console along with the
  17.   * size of the page.
  18.   */
  19. public void getWebSite() {
  20.  
  21. try {
  22.  
  23. URL url = new URL("http://www.google.com");
  24. URLConnection urlc = url.openConnection();
  25.  
  26. BufferedInputStream buffer = new BufferedInputStream(urlc.getInputStream());
  27.  
  28. StringBuilder builder = new StringBuilder();
  29. int byteRead;
  30. while ((byteRead = buffer.read()) != -1)
  31. builder.append((char) byteRead);
  32.  
  33. buffer.close();
  34.  
  35. System.out.println(builder.toString());
  36. System.out.println("The size of the web page is " + builder.length() + " bytes.");
  37.  
  38. } catch (MalformedURLException ex) {
  39. ex.printStackTrace();
  40. } catch (IOException ex) {
  41. ex.printStackTrace();
  42. }
  43. }
  44. /**
  45.   * Starts the program
  46.   *
  47.   * @param args the command line arguments
  48.   */
  49. public static void main(String[] args) {
  50. new Main().getWebSite();
  51. }
  52. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.