Java URL Class

Last updated on Dec 27 2022
Prabhas Ramanathan

The Java URL class represents an URL. URL is an acronym for Uniform Resource Locator. It points to a resource on the World Wide Web. For example:
1. https://www.tecklearn.com/java-section
A URL contains many information:
1. Protocol: In this case, http is the protocol.
2. Server name or IP Address: In this case, www.tecklearn.com is the server name.
3. Port Number: It is an optional attribute. If we write http//ww.tecklearn.com:80/sonoojaiswal/ , 80 is the port number. If port number is not mentioned in the URL, it returns -1.
4. File Name or directory name: In this case, index.jsp is the file name.

Table of Contents

Constructors of Java URL class

URL(String spec)

Creates an instance of a URL from the String representation.

URL(String protocol, String host, int port, String file)

Creates an instance of a URL from the given protocol, host, port number, and file.

URL(String protocol, String host, int port, String file, URLStreamHandler handler)

Creates an instance of a URL from the given protocol, host, port number, file, and handler.

URL(String protocol, String host, String file)

Creates an instance of a URL from the given protocol name, host name, and file name.

URL(URL context, String spec)

Creates an instance of a URL by parsing the given spec within a specified context.

URL(URL context, String spec, URLStreamHandler handler)

Creates an instance of a URL by parsing the given spec with the specified handler within a given context.

Commonly used methods of Java URL class

The java.net.URL class provides many methods. The important methods of URL class are given below.

Method Description
public String getProtocol() it returns the protocol of the URL.
public String getHost() it returns the host name of the URL.
public String getPort() it returns the Port Number of the URL.
public String getFile() it returns the file name of the URL.
public String getAuthority() it returns the authority of the URL.
public String toString() it returns the string representation of the URL.
public String getQuery() it returns the query string of the URL.
public String getDefaultPort() it returns the default port of the URL.
public URLConnection openConnection() it returns the instance of URLConnection i.e. associated with this URL.
public boolean equals(Object obj) it compares the URL with the given object.
public Object getContent() it returns the content of the URL.
public String getRef() it returns the anchor or reference of the URL.
public URI toURI() it returns a URI of the URL.

Example of Java URL class

1. //URLDemo.java 
2. import java.net.*; 
3. public class URLDemo{ 
4. public static void main(String[] args){ 
5. try{ 
6. URL url=new URL("http://www.tecklearn.com/java-section"); 
7. 
8. System.out.println("Protocol: "+url.getProtocol()); 
9. System.out.println("Host Name: "+url.getHost()); 
10. System.out.println("Port Number: "+url.getPort()); 
11. System.out.println("File Name: "+url.getFile()); 
12. 
13. }catch(Exception e){System.out.println(e);} 
14. } 
15. }

Output:

Protocol: http
Host Name: www.tecklearn.com
Port Number: -1
File Name: /java-section

Let us see another example URL class in Java.

1. //URLDemo.java 
2. import java.net.*; 
3. public class URLDemo{ 
4. public static void main(String[] args){ 
5. try{ 
6. URL url=new URL("https://www.google.com/search?q=tecklearn&oq=tecklearn&sourceid=chrome&ie=UTF-8"); 
7. 
8. System.out.println("Protocol: "+url.getProtocol()); 
9. System.out.println("Host Name: "+url.getHost()); 
10. System.out.println("Port Number: "+url.getPort()); 
11. System.out.println("Default Port Number: "+url.getDefaultPort()); 
12. System.out.println("Query String: "+url.getQuery()); 
13. System.out.println("Path: "+url.getPath()); 
14. System.out.println("File: "+url.getFile()); 
15. 
16. }catch(Exception e){System.out.println(e);} 
17. } 
18. }

Output:
Protocol: https
Host Name: www.google.com
Port Number: -1
Default Port Number: 443
Query String: q=tecklearn&oq=tecklearn&sourceid=chrome&ie=UTF-8
Path: /search
File: /search?q=tecklearn&oq=tecklearn&sourceid=chrome&ie=UTF-8

Java URLConnection class

The Java URLConnection class represents a communication link between the URL and the application. This class can be used to read and write data to the specified resource referred by the URL.

How to get the object of URLConnection class

The openConnection() method of URL class returns the object of URLConnection class. Syntax:
1. public URLConnection openConnection()throws IOException{}

Displaying source code of a webpage by URLConnecton class

The URLConnection class provides many methods, we can display all the data of a webpage by using the getInputStream() method. The getInputStream() method returns all the data of the specified URL in the stream that can be read and displayed.

Example of Java URLConnection class

1. import java.io.*; 
2. import java.net.*; 
3. public class URLConnectionExample { 
4. public static void main(String[] args){ 
5. try{ 
6. URL url=new URL("http://www.tecklearn.com/java-section"); 
7. URLConnection urlcon=url.openConnection(); 
8. InputStream stream=urlcon.getInputStream(); 
9. int i; 
10. while((i=stream.read())!=-1){ 
11. System.out.print((char)i); 
12. } 
13. }catch(Exception e){System.out.println(e);} 
14. } 
15. } 

Java HttpURLConnection class

The Java HttpURLConnection class is http specific URLConnection. It works for HTTP protocol only.
By the help of HttpURLConnection class, you can information of any HTTP URL such as header information, status code, response code etc.
The java.net.HttpURLConnection is subclass of URLConnection class.

How to get the object of HttpURLConnection class

The openConnection() method of URL class returns the object of URLConnection class. Syntax:
1. public URLConnection openConnection()throws IOException{}
You can typecast it to HttpURLConnection type as given below.
1. URL url=new URL(“http://www.tecklearn.com/java-section”);
2. HttpURLConnection huc=(HttpURLConnection)url.openConnection();

Java HttpURLConnecton Example

1. import java.io.*; 
2. import java.net.*; 
3. public class HttpURLConnectionDemo{ 
4. public static void main(String[] args){ 
5. try{ 
6. URL url=new URL("http://www.tecklearn.com/java-section"); 
7. HttpURLConnection huc=(HttpURLConnection)url.openConnection(); 
8. for(int i=1;i<=8;i++){ 
9. System.out.println(huc.getHeaderFieldKey(i)+" = "+huc.getHeaderField(i)); 
10. } 
11. huc.disconnect(); 
12. }catch(Exception e){System.out.println(e);} 
13. } 
14. }

Test it Now
Output:
Date = Wed, 10 Dec 2014 19:31:14 GMT
Set-Cookie = JSESSIONID=D70B87DBB832820CACA5998C90939D48; Path=/
Content-Type = text/html
Cache-Control = max-age=2592000
Expires = Fri, 09 Jan 2015 19:31:14 GMT
Vary = Accept-Encoding,User-Agent
Connection = close
Transfer-Encoding = chunked

Java InetAddress class

Java InetAddress class represents an IP address. The java.net.InetAddress class provides methods to get the IP of any host name for example www.tecklearn.com, www.google.com, www.facebook.com, etc.
An IP address is represented by 32-bit or 128-bit unsigned number. An instance of InetAddress represents the IP address with its corresponding host name. There are two types of address types: Unicast and Multicast. The Unicast is an identifier for a single interface whereas Multicast is an identifier for a set of interfaces.
Moreover, InetAddress has a cache mechanism to store successful and unsuccessful host name resolutions.

Commonly used methods of InetAddress class

Method Description
public static InetAddress getByName(String host) throws UnknownHostException it returns the instance of InetAddress containing LocalHost IP and name.
public static InetAddress getLocalHost() throws UnknownHostException it returns the instance of InetAdddress containing local host name and address.
public String getHostName() it returns the host name of the IP address.
public String getHostAddress() it returns the IP address in string format.

Example of Java InetAddress class

Let’s see a simple example of InetAddress class to get ip address of www.tecklearn.com website.

1. import java.io.*; 
2. import java.net.*; 
3. public class InetDemo{ 
4. public static void main(String[] args){ 
5. try{ 
6. InetAddress ip=InetAddress.getByName("www.tecklearn.com"); 
7. 
8. System.out.println("Host Name: "+ip.getHostName()); 
9. System.out.println("IP Address: "+ip.getHostAddress()); 
10. }catch(Exception e){System.out.println(e);} 
11. } 
12. }

Test it Now
Output:
Host Name: www.tecklearn.com
IP Address: 206.51.231.148

Java DatagramSocket and DatagramPacket

Java DatagramSocket and DatagramPacket classes are used for connection-less socket programming.

Java DatagramSocket class

Java DatagramSocket class represents a connection-less socket for sending and receiving datagram packets.
A datagram is basically an information but there is no guarantee of its content, arrival or arrival time.

Commonly used Constructors of DatagramSocket class

• DatagramSocket() throws SocketEeption: it creates a datagram socket and binds it with the available Port Number on the localhost machine.
• DatagramSocket(int port) throws SocketEeption: it creates a datagram socket and binds it with the given Port Number.
• DatagramSocket(int port, InetAddress address) throws SocketEeption: it creates a datagram socket and binds it with the specified port number and host address.

Java DatagramPacket class

Java DatagramPacket is a message that can be sent or received. If you send multiple packet, it may arrive in any order. Additionally, packet delivery is not guaranteed.

Commonly used Constructors of DatagramPacket class

• DatagramPacket(byte[] barr, int length): it creates a datagram packet. This constructor is used to receive the packets.
• DatagramPacket(byte[] barr, int length, InetAddress address, int port): it creates a datagram packet. This constructor is used to send the packets.

Example of Sending DatagramPacket by DatagramSocket

1. //DSender.java 
2. import java.net.*; 
3. public class DSender{ 
4. public static void main(String[] args) throws Exception { 
5. DatagramSocket ds = new DatagramSocket(); 
6. String str = "Welcome java"; 
7. InetAddress ip = InetAddress.getByName("127.0.0.1"); 
8. 
9. DatagramPacket dp = new DatagramPacket(str.getBytes(), str.length(), ip, 3000); 
10. ds.send(dp); 
11. ds.close(); 
12. } 
13. }

Example of Receiving DatagramPacket by DatagramSocket

1. //DReceiver.java 
2. import java.net.*; 
3. public class DReceiver{ 
4. public static void main(String[] args) throws Exception { 
5. DatagramSocket ds = new DatagramSocket(3000); 
6. byte[] buf = new byte[1024]; 
7. DatagramPacket dp = new DatagramPacket(buf, 1024); 
8. ds.receive(dp); 
9. String str = new String(dp.getData(), 0, dp.getLength()); 
10. System.out.println(str); 
11. ds.close(); 
12. } 
13. }

So, this brings us to the end of blog. This Tecklearn ‘Java URL Class’ blog helps you with commonly asked questions if you are looking out for a job in Java Programming. If you wish to learn Java and build a career Java Programming domain, then check out our interactive, Java and JEE Training, that comes with 24*7 support to guide you throughout your learning period. Please find the link for course details:

Java and JEE Training

Java and JEE Training

About the Course

Java and JEE Certification Training is designed by professionals as per the industrial requirements and demands. This training encompasses comprehensive knowledge on basic and advanced concepts of core Java & J2EE along with popular frameworks like Hibernate, Spring & SOA. In this course, you will gain expertise in concepts like Java Array, Java OOPs, Java Function, Java Loops, Java Collections, Java Thread, Java Servlet, and Web Services using industry use-cases and this will help you to become a certified Java expert.

Why Should you take Java and JEE Training?

• Java developers are in great demand in the job market. With average pay going between $90,000/- to $120,000/- depending on your experience and the employers.
• Used by more than 10 Million developers worldwide to develop applications for 15 Billion devices.
• Java is one of the most popular programming languages in the software world. Rated #1 in TIOBE Popular programming languages index (15th Consecutive Year)

What you will Learn in this Course?

Introduction to Java

• Java Fundamentals
• Introduction to Java Basics
• Features of Java
• Various components of Java language
• Benefits of Java over other programming languages
• Key Benefits of Java

Installation and IDE’s for Java Programming Language

• Installation of Java
• Setting up of Eclipse IDE
• Components of Java Program
• Editors and IDEs used for Java Programming
• Writing a Simple Java Program

Data Handling and Functions

• Data types, Operations, Compilation process, Class files, Loops, Conditions
• Using Loop Constructs
• Arrays- Single Dimensional and Multi-Dimensional
• Functions
• Functions with Arguments

OOPS in Java: Concept of Object Orientation

• Object Oriented Programming in Java
• Implement classes and objects in Java
• Create Class Constructors
• Overload Constructors
• Inheritance
• Inherit Classes and create sub-classes
• Implement abstract classes and methods
• Use static keyword
• Implement Interfaces and use it

 

Polymorphism, Packages and String Handling

• Concept of Static and Run time Polymorphism
• Function Overloading
• String Handling –String Class
• Java Packages

Exception Handling and Multi-Threading

• Exception handling
• Various Types of Exception Handling
• Introduction to multi-threading in Java
• Extending the thread class
• Synchronizing the thread

File Handling in Java

• Input Output Streams
• Java.io Package
• File Handling in Java

Java Collections

• Wrapper Classes and Inner Classes: Integer, Character, Boolean, Float etc
• Applet Programs: How to write UI programs with Applet, Java.lang, Java.io, Java.util
• Collections: ArrayList, Vector, HashSet, TreeSet, HashMap, HashTable

Java Database Connectivity (JDBC)

• Introduction to SQL: Connect, Insert, Update, Delete, Select
• Introduction to JDBC and Architecture of JDBC
• Insert/Update/Delete/Select Operations using JDBC
• Batch Processing Transaction
• Management: Commit and Rollback

Java Enterprise Edition – Servlets

• Introduction to J2EE
• Client Server architecture
• URL, Port Number, Request, Response
• Need for servlets
• Servlet fundamentals
• Setting up a web project in Eclipse
• Configuring and running the web app with servlets
• GET and POST request in web application with demo
• Servlet lifecycle
• Servlets Continued
• Session tracking and filter
• Forward and include Servlet request dispatchers

Java Server Pages (JSP)

• Fundamentals of Java Server Page
• Writing a code using JSP
• The architecture of JSP
• JSP Continued
• JSP elements: Scriptlets, expressions, declaration
• JSP standard actions
• JSP directives
• Introduction to JavaBeans
• ServletConfig and ServletContext
• Servlet Chaining
• Cookies Management
• Session Management

Hibernate

• Introduction to Hibernate
• Introduction to ORM
• ORM features
• Hibernate as an ORM framework
• Hibernate features
• Setting up a project with Hibernate framework
• Basic APIs needed to do CRUD operations with Hibernate
• Hibernate Architecture

POJO (Plain Old Java Object)

• POJO (Plain Old Java Object)
• Persistent Objects
• Lifecycle of Persistent Object

Spring

• Introduction to Spring
• Spring Fundamentals
• Advanced Spring

Got a question for us? Please mention it in the comments section and we will get back to you.

 

 

0 responses on "Java URL Class"

Leave a Message

Your email address will not be published. Required fields are marked *