Java url urlconnection
In Java, the URL
and URLConnection
classes are used to connect to a web server and retrieve data from it. The URL
class represents a Uniform Resource Locator (URL), which is the address of a web page, while the URLConnection
class represents a connection to that URL.
Here is an example of how to use URL
and URLConnection
in Java:
import java.net.*; public class URLDemo { public static void main(String[] args) { try { URL url = new URL("https://www.example.com"); URLConnection connection = url.openConnection(); connection.connect(); System.out.println("Content-Type: " + connection.getContentType()); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; while ((line = reader.readLine()) != null) { System.out.println(line); } reader.close(); } catch (IOException e) { e.printStackTrace(); } } }Sourci.www:egiftidea.com
In this example, a URL
object is created using the address "https://www.example.com". The openConnection()
method is called on the URL
object to create a URLConnection
object, which represents the connection to the URL. The connect()
method is called on the URLConnection
object to establish the connection.
Once the connection is established, the getContentType()
method is called on the URLConnection
object to get the content type of the resource at the URL, which is printed to the console. The getInputStream()
method is called on the URLConnection
object to retrieve the data from the URL as an input stream. This input stream is then wrapped in a BufferedReader
, which is used to read the data line by line and print it to the console.
Note that the IOException
is thrown in case there is an error in opening a connection or reading data from it.
It is important to close the BufferedReader
object and the connection using the close()
method once we are done working with them, in order to free up system resources.