4

How we can Download a HTML Page using JAVA??

James P.
  • 19,313
  • 27
  • 97
  • 155
  • Hi Binu, the following link should be of interest. http://stackoverflow.com/questions/2664404/retrieving-a-web-page-including-embedded-objects – James P. Jul 27 '10 at 07:35
  • possible duplicate of [Download file by passing URL using java code](http://stackoverflow.com/questions/2302233/download-file-by-passing-url-using-java-code) – McDowell Jul 27 '10 at 07:37
  • @McDowell,@James P : sorry, i dont know that there is some other with same questions –  Jul 27 '10 at 07:41
  • Your question is seems to be little bit confusing whether you want to download html file from any server or you want to fetch html web page? – Rupeshit Jul 27 '10 at 07:46
  • @Rupeshit : ya thats the word fetch... –  Jul 27 '10 at 07:49
  • @Binu: No worries. Sometimes a question can add something to what already exists. While you're browsing around, take a look at the related section of each question. Sometimes the links there are worth a read. – James P. Jul 27 '10 at 08:03
  • @James : Thks James, i will check the stuff when i do next time –  Jul 27 '10 at 08:06

3 Answers3

10

Here is the code:

public static String savePage(final String URL) throws IOException {
    String line = "", all = "";
    URL myUrl = null;
    BufferedReader in = null;
    try {
        myUrl = new URL(URL);
        in = new BufferedReader(new InputStreamReader(myUrl.openStream()));

        while ((line = in.readLine()) != null) {
            all += line;
        }
    } finally {
        if (in != null) {
            in.close();
        }
    }

    return all;
}

Now you can process one line after one other in the while loop.

Jared Burrows
  • 54,294
  • 25
  • 151
  • 185
Klark
  • 8,162
  • 3
  • 37
  • 61
2

If you have more requirements, like authentication, you can use HttpClient

rlovtang
  • 4,860
  • 2
  • 30
  • 30
2

If you can use Groovy, which compiles to java bytecode, you can fetch a page like this:

String text = new URL("http://google.com").text
rlovtang
  • 4,860
  • 2
  • 30
  • 30