SlideShare a Scribd company logo
1 of 13
Download to read offline
URL Class in Java
Anybody who uses the internet these days would have come across a URL. It is a
unique string of text that is an identity for the resources available on the internet. To
put it in simple words, a URL is an address for the resources that we can find on the
internet. This article explains the URL class in Java. Let’s start!!
What is a URL?
The term URL is an acronym for Uniform Resource Locator. It denotes a resource
that is present on the World Wide Web. This resource might be an HTML page, file,
or document that is present on the World Wide Web.
Segments of a URL:
Though a URL might consist of several components, it consists of three main parts.:
1. Protocol: In the above-given example, HTTP is the protocol. Some other
examples of protocols are HTTPS, FTP, and File.
2. Server name or IP address: The server machine where the resources are present
is denoted as the server’s name. Here, firstcode.com is the server name.
3. Filename: Here, the file name is “java-class-and-objects”.
4. Port number: Port number helps the URL connect with the web. In case of not
explicitly mentioning the URL, the default port number is used.
Java URL Class
The Java URL is the gateway to access any resource that is present on the web.
The object of the java.net.URL class denotes the URL and manages all the details
available in the URL string. This class consists of various methods to create an
object of the URL class.
S.No Constructor Description
1
URL(String address)
throwsMalformedURLException
It creates a URL object from the given
input String
2 URL(String protocol, String host, String file)
It creates a URL object from the input
protocol, host and file name.
3
URL(String protocol, String host, int port, String
file)
It creates a URL object from the
mentioned protocol, hostname, port
number and, file name.
4 URL(URL context, String spec)
It creates a URL object by passing the
String specifications that are given.
5
URL(String protocol, String host, int port, String
file, URLStreamHandler handler)
It creates a URL object from the given
protocol, hostname, port number, file,
and, handler.
6
URL(URL context, Strong spec,
URLStreamHandler handler)
It makes a URL by parsing the spec
with the input handler.
Methods of Java URL Class:
S.
N
Method Name Description
1 public String toString() It returns the given URL object in the string form.
2 public String getPath()
It returns the path of the URL. It returns null if the URL is
empty.
3 public String getQuery()
It gives the query part of the URL. This part of the URL is
present after the ‘?’ in it.
4 public String getAuthority()
It returns the authority part of the URL. And it returns null
if it is empty.
5 public String getHost() It gives the hostname related to the URL in IPv6 format
6 public String getFile() It returns the filename of the URL.
7 public int getPort() It returns the port number of the URL.
8 public int getDefaultPort() It returns the default port number that the URL uses.
9 public String getRef()
It returns the reference to the URL object. This reference
is the part represented by ‘#’ in the URL.
10 public String getProtocol() It returns the protocol associated with the URL.
11 public String getAuthority()
It returns the authority of the URL. It collects the
hostname and the port.
12 public URL toURL() It returns a URL of the mentioned URL.
13
public URLConnection
OpenConnection()
It returns an instance of the URLConnection, connected
with the particular URL.
14 public Object getContent()
It returns the content of the URL, and it is returned as an
Object.
Creating URL with Component Parts:
Let us now see how to create a URL using the SUL components like hostname,
filename, and protocol.
Sample code to create a URL with the URL components:
import java.net.MalformedURLException;
import java.net.URL;
public class URLClassDemo
{
public static void main(String[ ] args) throws MalformedURLException
{
String protocol = "http";
String host = "firstcode.com";
String file = "/courses/java-url-class/";
URL url = new URL(protocol, host, file);
System.out.println("The URL is: " +url.toString());
}
}
Output:
The URL is: http://firstcode.com/courses/java-url-class
Sample program to implement the URL Class of Java:
import java.net.MalformedURLException;
import java.net.URL;
public class URLClassDemo
{
public static void main(String[] args) throws MalformedURLException
{
URL url1 = new URL("https://firstcode.com/courses/java-encapsulation/");
System.out.println("url1 is: " +url1.toString());
System.out.println("nVarious components of the url1");
System.out.println("Protocol: " + url1.getProtocol());
System.out.println("Hostname: " + url1.getHost());
System.out.println("Port: " + url1.getPort());
System.out.println("Default port: " + url1.getDefaultPort());
System.out.println("Query: " + url1.getQuery());
System.out.println("Path: " + url1.getPath());
System.out.println("File: " + url1.getFile());
System.out.println("Reference: " + url1.getRef());
System.out.println("Authority: " + url1.getAuthority());
}
Output:
url1 is: https://firstcode.com/courses/java-encapsulation/Various components of the
url1
Protocol: https
Hostname: firstcode.com
Port: -1
Default port: 443
Query: null
Path: /courses/java-encapsulation/
File: /courses/java-encapsulation/
Reference: null
Authority: firstcode.com
URL Connection class in Java:
The URLConnection class in Java is important to represent a connection or
communication between an application and the URL. it helps the programmers to
read and write data to the given resource of the URL.
The java.net.URLConnection is an abstract class that has its subclasses
representing the different types of URL connections.
For example:
■ The openConnection() method returns the object of the
HttpURLConnection class. This takes place when we connect to a URL
using the HTTP protocol.
■ The openConnection() method returns the object of a JarURLConnection
class. this happens if we connect a JAR file to a URL.
Java OpenConnection() method:
We can attain the object of the URLConnection class with the openConnection()
method of the URL class.
Syntax:
public URLConnection openConnection() throws IOException{}
Methods of URL Connection Class in
Java:
Sl.N
.
Method Description
1 Object getContent() It returns the contents of the URL connection.
2 String getContentEncoding()
It returns the value of the content-encoding
header field in the form of a String.
3 int getContentLength()
This method provides the value of the
content-length header field in the String form.
4 String getContentType()
It returns the value of the content-type header
field.
5 int getLastModified() It gives the value of the last-modified header field.
6 long getExpiration() It returns the value of the expired header field.
7 long getIfModifiedSince()
It returns the value of the object’s ifModifiedSince
field.
9
public void setDoInput(boolean
input)
The value true is passed as a parameter to this
method to specify that it will be used for
connection input.
10
public void setDoOutput(boolean
output)
We pass the parameter true to this method to
specify that we will use the connection output.
11
public InputStream getInputStream()
throws IOException
It returns the input stream of the URL connection
for reading from the resource.
12
public OutputStream
getOutputStream() throws
IOException
It returns the output stream of the URL connection
for writing to the resource.
13 public URL getURL()
Returns the URL of the connected
URLConnection object.
Example of the URLConnection class:
As we just saw the various methods that are present in the URLConnectionDemo
class, let us see an example program to implement it.
Sample program to implement URLConnection class:
import java.net.*;
import java.io.*;
public class URLConnectionDemo
{
public static void main(String[] args) throws MalformedURLException
{
try{
URL url = new URL("https://www.firstcode.com");
URLConnection urlConnection = url.openConnection();
HttpURLConnection connection = null;
if(urlConnection instanceof HttpURLConnection)
{
connection = (HttpURLConnection) urlConnection;
}
else
{
System.out.println("Please enter a HTTP URL: ");
return;
}
BufferedReader in = new BufferedReader(
new InputStreamReader(connection.getInputStream()));
String urlString = " ";
String current;
while((current = in.readLine()) != null)
{
urlString += current;
}
System.out.println(urlString);
} catch (IOException e)
{
e.printStackTrace();
}
}
}
Output:
…..a complete HTML content of the home page of firstcode.com…..
Illustration methods of Java URL class:
import java.net.*;
public class FirstCode
{
public static void main(String[] args)throws Exception{
String url="https://first-code/blogs/java-tutorial/";
URL testurl= new URL(url);
System.out.println("The String representation of the URL -> "+testurl.toString());
System.out.println("The Authority of the URL -> "+testurl.getAuthority());
System.out.println("The Path of the URL -> "+testurl.getPath());
System.out.println("The Query of the URL -> "+testurl.getQuery());
System.out.println("The Host of the URL -> "+testurl.getHost());
System.out.println("The File of the URL -> "+testurl.getFile());
System.out.println("The Port of the URL -> "+testurl.getPort());
System.out.println("The Default port of the URL -> "+testurl.getDefaultPort());
System.out.println("The Protocol of the URL -> "+testurl.getProtocol());
System.out.println("As no certain values can be parsed, the results are null or -1 in
various cases, but there are no particular values.");
}
}
Output:
The string representation of the URL -> https://first-code/blogs/java-tutorial/
The Authority of the URL -> first-code.training
The Path of the URL -> /blogs/java-tutorial/
The Query of the URL -> null
The host of the URL -> first-code.training
The file of the URL -> /blogs/java-tutorial/
The port of the URL -> -1
The default port of the URL -> 443
The protocol of the URL -> https
As no certain values can be parsed, the results are null or -1 in various cases, but
there are no particular values.
Sample program to implement url class in Java:
import java.net.MalformedURLException;
import java.net.URL;
public class FirstCode
{
public static void main(String[] args)throws MalformedURLException
{
URL url1 = new URL("https://www.google.co.in/?gfe_rd=cr&ei=ptYq" +
"WK26I4fT8gfth6CACg#q=first+code+java+tutorials");
// creates a URL with a protocol,hostname,and path
URL url2 = new URL("http", "www.firstcode.com", "/jvm-works-jvm-architecture/");
URL url3 = new URL("https://www.google.co.in/search?"+ "q=gnu&rlz=1C1CHZL_enIN71" +
"4IN715&oq=gnu&aqs=chrome..69i57j6" +"9i60l5.653j0j7&sourceid=chrome&ie=UTF" +
"-8#q=first+code+java+tutorials");
// print the string representation of the URL.
System.out.println(url1.toString());
System.out.println(url2.toString());
System.out.println();
System.out.println("Different components of the URL3-");
// retrieve the protocol for the URL
System.out.println("Protocol:- " + url3.getProtocol());
// retrieve the hostname of the url
System.out.println("Hostname:- " + url3.getHost());
// retrieve the default port
System.out.println("Default port:- " +url3.getDefaultPort());
// retrieve the query part of URL
System.out.println("Query:- " + url3.getQuery());
// retrieve the path of URL
System.out.println("Path:- " + url3.getPath());
// retrieve the file name
System.out.println("File:- " + url3.getFile());
// retrieve the reference
System.out.println("Reference:- " + url3.getRef());
}
}
Output:
https://www.google.co.in/?gfe_rd=cr&ei=ptYqWK26I4fT8gfth6CACg#q=
first+code+java+tutorials
https://www.first+code+java+tutorials/jvm-works-jvm-architecture/
Different components of the URL3-
Protocol -> https
Hostname -> www.google.co.in
Default port -> 443
Query ->
q=gnu&rlz=1C1CHZL_enIN1416LK15&oq=gnu&aws=chrome..69i57j&sourceid=chro
me&ie=UTF-8
Path -> /search
File ->
/search?q=gnu&rlz=1C1CHZL_enIN714IN715&oq=gnu&as=chrome..69i57898015.6
523joj7&sourceid-chrome&ie=UTF-8
References –> q=first+code+blogs+tutorial
Conclusion
The URL class is inevitable in the internet era. In this tutorial, we learned about the
Java URL, its constructors, and methods. Now, you can easily establish the URL
connection class to connect with an application.

More Related Content

Similar to URL Class in Java.pdf

Unit8 java
Unit8 javaUnit8 java
Unit8 javamrecedu
 
The Django Book / Chapter 3: Views and URLconfs
The Django Book / Chapter 3: Views and URLconfsThe Django Book / Chapter 3: Views and URLconfs
The Django Book / Chapter 3: Views and URLconfsVincent Chien
 
create-netflix-clone-02-server.pdf
create-netflix-clone-02-server.pdfcreate-netflix-clone-02-server.pdf
create-netflix-clone-02-server.pdfShaiAlmog1
 
Lambda Chops - Recipes for Simpler, More Expressive Code
Lambda Chops - Recipes for Simpler, More Expressive CodeLambda Chops - Recipes for Simpler, More Expressive Code
Lambda Chops - Recipes for Simpler, More Expressive CodeIan Robertson
 
Swift LA Meetup at eHarmony- What's New in Swift 2.0
Swift LA Meetup at eHarmony- What's New in Swift 2.0Swift LA Meetup at eHarmony- What's New in Swift 2.0
Swift LA Meetup at eHarmony- What's New in Swift 2.0Claire Townend Gee
 
Drupal 8 meets to symphony
Drupal 8 meets to symphonyDrupal 8 meets to symphony
Drupal 8 meets to symphonyBrahampal Singh
 
uniform resource locator
uniform resource locatoruniform resource locator
uniform resource locatorrajshreemuthiah
 
Android ui layouts ,cntls,webservices examples codes
Android ui layouts ,cntls,webservices examples codesAndroid ui layouts ,cntls,webservices examples codes
Android ui layouts ,cntls,webservices examples codesAravindharamanan S
 
Connecting to the network
Connecting to the networkConnecting to the network
Connecting to the networkMu Chun Wang
 
Client server part 12
Client server part 12Client server part 12
Client server part 12fadlihulopi
 
Asp.net server control
Asp.net  server controlAsp.net  server control
Asp.net server controlSireesh K
 

Similar to URL Class in Java.pdf (20)

Unit8 java
Unit8 javaUnit8 java
Unit8 java
 
Url programming
Url programmingUrl programming
Url programming
 
Java networking
Java networkingJava networking
Java networking
 
Ajax
AjaxAjax
Ajax
 
The Django Book / Chapter 3: Views and URLconfs
The Django Book / Chapter 3: Views and URLconfsThe Django Book / Chapter 3: Views and URLconfs
The Django Book / Chapter 3: Views and URLconfs
 
Corba
CorbaCorba
Corba
 
create-netflix-clone-02-server.pdf
create-netflix-clone-02-server.pdfcreate-netflix-clone-02-server.pdf
create-netflix-clone-02-server.pdf
 
Lambda Chops - Recipes for Simpler, More Expressive Code
Lambda Chops - Recipes for Simpler, More Expressive CodeLambda Chops - Recipes for Simpler, More Expressive Code
Lambda Chops - Recipes for Simpler, More Expressive Code
 
Apache Beam de A à Z
 Apache Beam de A à Z Apache Beam de A à Z
Apache Beam de A à Z
 
Jsoup tutorial
Jsoup tutorialJsoup tutorial
Jsoup tutorial
 
Advance Java
Advance JavaAdvance Java
Advance Java
 
Swift LA Meetup at eHarmony- What's New in Swift 2.0
Swift LA Meetup at eHarmony- What's New in Swift 2.0Swift LA Meetup at eHarmony- What's New in Swift 2.0
Swift LA Meetup at eHarmony- What's New in Swift 2.0
 
SPARQLing cocktails
SPARQLing cocktailsSPARQLing cocktails
SPARQLing cocktails
 
Drupal 8 meets to symphony
Drupal 8 meets to symphonyDrupal 8 meets to symphony
Drupal 8 meets to symphony
 
uniform resource locator
uniform resource locatoruniform resource locator
uniform resource locator
 
Android ui layouts ,cntls,webservices examples codes
Android ui layouts ,cntls,webservices examples codesAndroid ui layouts ,cntls,webservices examples codes
Android ui layouts ,cntls,webservices examples codes
 
Scmad Chapter09
Scmad Chapter09Scmad Chapter09
Scmad Chapter09
 
Connecting to the network
Connecting to the networkConnecting to the network
Connecting to the network
 
Client server part 12
Client server part 12Client server part 12
Client server part 12
 
Asp.net server control
Asp.net  server controlAsp.net  server control
Asp.net server control
 

More from SudhanshiBakre1

Float Data Type in C.pdf
Float Data Type in C.pdfFloat Data Type in C.pdf
Float Data Type in C.pdfSudhanshiBakre1
 
IoT Hardware – The Backbone of Smart Devices.pdf
IoT Hardware – The Backbone of Smart Devices.pdfIoT Hardware – The Backbone of Smart Devices.pdf
IoT Hardware – The Backbone of Smart Devices.pdfSudhanshiBakre1
 
Internet of Things – Contiki.pdf
Internet of Things – Contiki.pdfInternet of Things – Contiki.pdf
Internet of Things – Contiki.pdfSudhanshiBakre1
 
Java abstract Keyword.pdf
Java abstract Keyword.pdfJava abstract Keyword.pdf
Java abstract Keyword.pdfSudhanshiBakre1
 
Collections in Python - Where Data Finds Its Perfect Home.pdf
Collections in Python - Where Data Finds Its Perfect Home.pdfCollections in Python - Where Data Finds Its Perfect Home.pdf
Collections in Python - Where Data Finds Its Perfect Home.pdfSudhanshiBakre1
 
File Handling in Java.pdf
File Handling in Java.pdfFile Handling in Java.pdf
File Handling in Java.pdfSudhanshiBakre1
 
Types of AI you should know.pdf
Types of AI you should know.pdfTypes of AI you should know.pdf
Types of AI you should know.pdfSudhanshiBakre1
 
Annotations in Java with Example.pdf
Annotations in Java with Example.pdfAnnotations in Java with Example.pdf
Annotations in Java with Example.pdfSudhanshiBakre1
 
Top Cryptocurrency Exchanges of 2023.pdf
Top Cryptocurrency Exchanges of 2023.pdfTop Cryptocurrency Exchanges of 2023.pdf
Top Cryptocurrency Exchanges of 2023.pdfSudhanshiBakre1
 
Epic Python Face-Off -Methods vs.pdf
Epic Python Face-Off -Methods vs.pdfEpic Python Face-Off -Methods vs.pdf
Epic Python Face-Off -Methods vs.pdfSudhanshiBakre1
 
Django Tutorial_ Let’s take a deep dive into Django’s web framework.pdf
Django Tutorial_ Let’s take a deep dive into Django’s web framework.pdfDjango Tutorial_ Let’s take a deep dive into Django’s web framework.pdf
Django Tutorial_ Let’s take a deep dive into Django’s web framework.pdfSudhanshiBakre1
 
Benefits Of IoT Salesforce.pdf
Benefits Of IoT Salesforce.pdfBenefits Of IoT Salesforce.pdf
Benefits Of IoT Salesforce.pdfSudhanshiBakre1
 
Epic Python Face-Off -Methods vs. Functions.pdf
Epic Python Face-Off -Methods vs. Functions.pdfEpic Python Face-Off -Methods vs. Functions.pdf
Epic Python Face-Off -Methods vs. Functions.pdfSudhanshiBakre1
 
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdfPython Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdfSudhanshiBakre1
 

More from SudhanshiBakre1 (20)

IoT Security.pdf
IoT Security.pdfIoT Security.pdf
IoT Security.pdf
 
Top Java Frameworks.pdf
Top Java Frameworks.pdfTop Java Frameworks.pdf
Top Java Frameworks.pdf
 
Numpy ndarrays.pdf
Numpy ndarrays.pdfNumpy ndarrays.pdf
Numpy ndarrays.pdf
 
Float Data Type in C.pdf
Float Data Type in C.pdfFloat Data Type in C.pdf
Float Data Type in C.pdf
 
IoT Hardware – The Backbone of Smart Devices.pdf
IoT Hardware – The Backbone of Smart Devices.pdfIoT Hardware – The Backbone of Smart Devices.pdf
IoT Hardware – The Backbone of Smart Devices.pdf
 
Internet of Things – Contiki.pdf
Internet of Things – Contiki.pdfInternet of Things – Contiki.pdf
Internet of Things – Contiki.pdf
 
Java abstract Keyword.pdf
Java abstract Keyword.pdfJava abstract Keyword.pdf
Java abstract Keyword.pdf
 
Node.js with MySQL.pdf
Node.js with MySQL.pdfNode.js with MySQL.pdf
Node.js with MySQL.pdf
 
Collections in Python - Where Data Finds Its Perfect Home.pdf
Collections in Python - Where Data Finds Its Perfect Home.pdfCollections in Python - Where Data Finds Its Perfect Home.pdf
Collections in Python - Where Data Finds Its Perfect Home.pdf
 
File Handling in Java.pdf
File Handling in Java.pdfFile Handling in Java.pdf
File Handling in Java.pdf
 
Types of AI you should know.pdf
Types of AI you should know.pdfTypes of AI you should know.pdf
Types of AI you should know.pdf
 
Streams in Node .pdf
Streams in Node .pdfStreams in Node .pdf
Streams in Node .pdf
 
Annotations in Java with Example.pdf
Annotations in Java with Example.pdfAnnotations in Java with Example.pdf
Annotations in Java with Example.pdf
 
RESTful API in Node.pdf
RESTful API in Node.pdfRESTful API in Node.pdf
RESTful API in Node.pdf
 
Top Cryptocurrency Exchanges of 2023.pdf
Top Cryptocurrency Exchanges of 2023.pdfTop Cryptocurrency Exchanges of 2023.pdf
Top Cryptocurrency Exchanges of 2023.pdf
 
Epic Python Face-Off -Methods vs.pdf
Epic Python Face-Off -Methods vs.pdfEpic Python Face-Off -Methods vs.pdf
Epic Python Face-Off -Methods vs.pdf
 
Django Tutorial_ Let’s take a deep dive into Django’s web framework.pdf
Django Tutorial_ Let’s take a deep dive into Django’s web framework.pdfDjango Tutorial_ Let’s take a deep dive into Django’s web framework.pdf
Django Tutorial_ Let’s take a deep dive into Django’s web framework.pdf
 
Benefits Of IoT Salesforce.pdf
Benefits Of IoT Salesforce.pdfBenefits Of IoT Salesforce.pdf
Benefits Of IoT Salesforce.pdf
 
Epic Python Face-Off -Methods vs. Functions.pdf
Epic Python Face-Off -Methods vs. Functions.pdfEpic Python Face-Off -Methods vs. Functions.pdf
Epic Python Face-Off -Methods vs. Functions.pdf
 
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdfPython Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
 

Recently uploaded

ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 

Recently uploaded (20)

ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 

URL Class in Java.pdf

  • 1. URL Class in Java Anybody who uses the internet these days would have come across a URL. It is a unique string of text that is an identity for the resources available on the internet. To put it in simple words, a URL is an address for the resources that we can find on the internet. This article explains the URL class in Java. Let’s start!! What is a URL? The term URL is an acronym for Uniform Resource Locator. It denotes a resource that is present on the World Wide Web. This resource might be an HTML page, file, or document that is present on the World Wide Web. Segments of a URL: Though a URL might consist of several components, it consists of three main parts.: 1. Protocol: In the above-given example, HTTP is the protocol. Some other examples of protocols are HTTPS, FTP, and File. 2. Server name or IP address: The server machine where the resources are present is denoted as the server’s name. Here, firstcode.com is the server name. 3. Filename: Here, the file name is “java-class-and-objects”. 4. Port number: Port number helps the URL connect with the web. In case of not explicitly mentioning the URL, the default port number is used. Java URL Class
  • 2. The Java URL is the gateway to access any resource that is present on the web. The object of the java.net.URL class denotes the URL and manages all the details available in the URL string. This class consists of various methods to create an object of the URL class. S.No Constructor Description 1 URL(String address) throwsMalformedURLException It creates a URL object from the given input String 2 URL(String protocol, String host, String file) It creates a URL object from the input protocol, host and file name. 3 URL(String protocol, String host, int port, String file) It creates a URL object from the mentioned protocol, hostname, port number and, file name. 4 URL(URL context, String spec) It creates a URL object by passing the String specifications that are given. 5 URL(String protocol, String host, int port, String file, URLStreamHandler handler) It creates a URL object from the given protocol, hostname, port number, file, and, handler. 6 URL(URL context, Strong spec, URLStreamHandler handler) It makes a URL by parsing the spec with the input handler. Methods of Java URL Class: S. N Method Name Description
  • 3. 1 public String toString() It returns the given URL object in the string form. 2 public String getPath() It returns the path of the URL. It returns null if the URL is empty. 3 public String getQuery() It gives the query part of the URL. This part of the URL is present after the ‘?’ in it. 4 public String getAuthority() It returns the authority part of the URL. And it returns null if it is empty. 5 public String getHost() It gives the hostname related to the URL in IPv6 format 6 public String getFile() It returns the filename of the URL. 7 public int getPort() It returns the port number of the URL. 8 public int getDefaultPort() It returns the default port number that the URL uses. 9 public String getRef() It returns the reference to the URL object. This reference is the part represented by ‘#’ in the URL. 10 public String getProtocol() It returns the protocol associated with the URL. 11 public String getAuthority() It returns the authority of the URL. It collects the hostname and the port. 12 public URL toURL() It returns a URL of the mentioned URL. 13 public URLConnection OpenConnection() It returns an instance of the URLConnection, connected with the particular URL.
  • 4. 14 public Object getContent() It returns the content of the URL, and it is returned as an Object. Creating URL with Component Parts: Let us now see how to create a URL using the SUL components like hostname, filename, and protocol. Sample code to create a URL with the URL components: import java.net.MalformedURLException; import java.net.URL; public class URLClassDemo { public static void main(String[ ] args) throws MalformedURLException { String protocol = "http"; String host = "firstcode.com"; String file = "/courses/java-url-class/"; URL url = new URL(protocol, host, file); System.out.println("The URL is: " +url.toString()); } } Output: The URL is: http://firstcode.com/courses/java-url-class
  • 5. Sample program to implement the URL Class of Java: import java.net.MalformedURLException; import java.net.URL; public class URLClassDemo { public static void main(String[] args) throws MalformedURLException { URL url1 = new URL("https://firstcode.com/courses/java-encapsulation/"); System.out.println("url1 is: " +url1.toString()); System.out.println("nVarious components of the url1"); System.out.println("Protocol: " + url1.getProtocol()); System.out.println("Hostname: " + url1.getHost()); System.out.println("Port: " + url1.getPort()); System.out.println("Default port: " + url1.getDefaultPort()); System.out.println("Query: " + url1.getQuery()); System.out.println("Path: " + url1.getPath()); System.out.println("File: " + url1.getFile()); System.out.println("Reference: " + url1.getRef()); System.out.println("Authority: " + url1.getAuthority()); } Output:
  • 6. url1 is: https://firstcode.com/courses/java-encapsulation/Various components of the url1 Protocol: https Hostname: firstcode.com Port: -1 Default port: 443 Query: null Path: /courses/java-encapsulation/ File: /courses/java-encapsulation/ Reference: null Authority: firstcode.com URL Connection class in Java: The URLConnection class in Java is important to represent a connection or communication between an application and the URL. it helps the programmers to read and write data to the given resource of the URL. The java.net.URLConnection is an abstract class that has its subclasses representing the different types of URL connections. For example: ■ The openConnection() method returns the object of the HttpURLConnection class. This takes place when we connect to a URL using the HTTP protocol. ■ The openConnection() method returns the object of a JarURLConnection class. this happens if we connect a JAR file to a URL. Java OpenConnection() method:
  • 7. We can attain the object of the URLConnection class with the openConnection() method of the URL class. Syntax: public URLConnection openConnection() throws IOException{} Methods of URL Connection Class in Java: Sl.N . Method Description 1 Object getContent() It returns the contents of the URL connection. 2 String getContentEncoding() It returns the value of the content-encoding header field in the form of a String. 3 int getContentLength() This method provides the value of the content-length header field in the String form. 4 String getContentType() It returns the value of the content-type header field. 5 int getLastModified() It gives the value of the last-modified header field. 6 long getExpiration() It returns the value of the expired header field. 7 long getIfModifiedSince() It returns the value of the object’s ifModifiedSince field.
  • 8. 9 public void setDoInput(boolean input) The value true is passed as a parameter to this method to specify that it will be used for connection input. 10 public void setDoOutput(boolean output) We pass the parameter true to this method to specify that we will use the connection output. 11 public InputStream getInputStream() throws IOException It returns the input stream of the URL connection for reading from the resource. 12 public OutputStream getOutputStream() throws IOException It returns the output stream of the URL connection for writing to the resource. 13 public URL getURL() Returns the URL of the connected URLConnection object. Example of the URLConnection class: As we just saw the various methods that are present in the URLConnectionDemo class, let us see an example program to implement it. Sample program to implement URLConnection class: import java.net.*; import java.io.*; public class URLConnectionDemo { public static void main(String[] args) throws MalformedURLException { try{
  • 9. URL url = new URL("https://www.firstcode.com"); URLConnection urlConnection = url.openConnection(); HttpURLConnection connection = null; if(urlConnection instanceof HttpURLConnection) { connection = (HttpURLConnection) urlConnection; } else { System.out.println("Please enter a HTTP URL: "); return; } BufferedReader in = new BufferedReader( new InputStreamReader(connection.getInputStream())); String urlString = " "; String current; while((current = in.readLine()) != null) { urlString += current; } System.out.println(urlString); } catch (IOException e) {
  • 10. e.printStackTrace(); } } } Output: …..a complete HTML content of the home page of firstcode.com….. Illustration methods of Java URL class: import java.net.*; public class FirstCode { public static void main(String[] args)throws Exception{ String url="https://first-code/blogs/java-tutorial/"; URL testurl= new URL(url); System.out.println("The String representation of the URL -> "+testurl.toString()); System.out.println("The Authority of the URL -> "+testurl.getAuthority()); System.out.println("The Path of the URL -> "+testurl.getPath()); System.out.println("The Query of the URL -> "+testurl.getQuery()); System.out.println("The Host of the URL -> "+testurl.getHost()); System.out.println("The File of the URL -> "+testurl.getFile()); System.out.println("The Port of the URL -> "+testurl.getPort()); System.out.println("The Default port of the URL -> "+testurl.getDefaultPort()); System.out.println("The Protocol of the URL -> "+testurl.getProtocol());
  • 11. System.out.println("As no certain values can be parsed, the results are null or -1 in various cases, but there are no particular values."); } } Output: The string representation of the URL -> https://first-code/blogs/java-tutorial/ The Authority of the URL -> first-code.training The Path of the URL -> /blogs/java-tutorial/ The Query of the URL -> null The host of the URL -> first-code.training The file of the URL -> /blogs/java-tutorial/ The port of the URL -> -1 The default port of the URL -> 443 The protocol of the URL -> https As no certain values can be parsed, the results are null or -1 in various cases, but there are no particular values. Sample program to implement url class in Java: import java.net.MalformedURLException; import java.net.URL; public class FirstCode { public static void main(String[] args)throws MalformedURLException { URL url1 = new URL("https://www.google.co.in/?gfe_rd=cr&ei=ptYq" + "WK26I4fT8gfth6CACg#q=first+code+java+tutorials");
  • 12. // creates a URL with a protocol,hostname,and path URL url2 = new URL("http", "www.firstcode.com", "/jvm-works-jvm-architecture/"); URL url3 = new URL("https://www.google.co.in/search?"+ "q=gnu&rlz=1C1CHZL_enIN71" + "4IN715&oq=gnu&aqs=chrome..69i57j6" +"9i60l5.653j0j7&sourceid=chrome&ie=UTF" + "-8#q=first+code+java+tutorials"); // print the string representation of the URL. System.out.println(url1.toString()); System.out.println(url2.toString()); System.out.println(); System.out.println("Different components of the URL3-"); // retrieve the protocol for the URL System.out.println("Protocol:- " + url3.getProtocol()); // retrieve the hostname of the url System.out.println("Hostname:- " + url3.getHost()); // retrieve the default port System.out.println("Default port:- " +url3.getDefaultPort()); // retrieve the query part of URL System.out.println("Query:- " + url3.getQuery()); // retrieve the path of URL System.out.println("Path:- " + url3.getPath()); // retrieve the file name System.out.println("File:- " + url3.getFile()); // retrieve the reference System.out.println("Reference:- " + url3.getRef());
  • 13. } } Output: https://www.google.co.in/?gfe_rd=cr&ei=ptYqWK26I4fT8gfth6CACg#q= first+code+java+tutorials https://www.first+code+java+tutorials/jvm-works-jvm-architecture/ Different components of the URL3- Protocol -> https Hostname -> www.google.co.in Default port -> 443 Query -> q=gnu&rlz=1C1CHZL_enIN1416LK15&oq=gnu&aws=chrome..69i57j&sourceid=chro me&ie=UTF-8 Path -> /search File -> /search?q=gnu&rlz=1C1CHZL_enIN714IN715&oq=gnu&as=chrome..69i57898015.6 523joj7&sourceid-chrome&ie=UTF-8 References –> q=first+code+blogs+tutorial Conclusion The URL class is inevitable in the internet era. In this tutorial, we learned about the Java URL, its constructors, and methods. Now, you can easily establish the URL connection class to connect with an application.