[Java] Reading a Webpage through URL

Most of the applications written these days require some or the other network feature. Stand-alone Java applications are rare occurence these days. In order to write a Java program which reads a Webpage, follow the steps mentioned below.

1.) Instantiate a URL object by passing the URL string to its constructor. [Line 16 in the code below]

2.) Retrieve a URLConnection object . [ Line 17 in the code below]

3.) Get an input stream from the connection. [Line 18-20 in the code below]

4.) Create a BufferedReader on the input stream and read from it. [Line 23-25 in the code below]

In the code mentioned below, i have tried reading http://technofriends.in

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

package testapplicationsfortechnofriends;
import java.net.*;
import java.io.*;
/**
*
* @author Vaibhav
*/
public class ReadURL {

public static void main(String[] args) throws Exception {
URL url = new URL("http://technofriends.in");
URLConnection tf = url.openConnection();
BufferedReader in = new BufferedReader(
new InputStreamReader(
tf.getInputStream()));
String inputLine;

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

Also read:[How-To] Print Date/Time in a Given Format in Java


Understanding Polymorphism in Java : Part 1


Understanding Polymorphism in Java : Part 2


What is the difference between JDK and JRE?


An introduction to JDBC Drivers


You can follow me on Twitter at http://twitter.com/vaibhav1981


Do stay tuned to Technofriends for more, one of the best ways of doing so is by subscribing to our feeds. You can subscribe to Technofriends feed by clicking here.


Cheers


Vaibhav



You have already tagged this post. Your tags:

Origianl story:

Valid XHTML 1.0 Strict