Page 1 of 12
Home Whiteboard Online Compilers Practice Articles Tools
Chapters Categories
Java - URL Processing
URL stands for Uniform Resource Locator and represents a resource on the World Wide
Web, such as a Web page or FTP directory.
This section shows you how to write Java programs that communicate with a URL. A URL
can be broken down into parts, as follows −
protocol://host:port/path?query#ref
Examples of protocols include HTTP, HTTPS, FTP, and File. The path is also referred to as
the filename, and the host is also called the authority.
The following is a URL to a web page whose protocol is HTTP −
https://www.amrood.com/index.htm?language=en#j2se
Notice that this URL does not specify a port, in which case the default port for the protocol
is used. With HTTP, the default port is 80.
Constructors
The java.net.URL class represents a URL and has a complete set of methods to
manipulate URL in Java.
The URL class has several constructors for creating URLs, including the following −
Sr.No. Constructors & Description
public URL(String protocol, String host, int port, String file) throws
1 MalformedURLException
Creates a URL by putting together the given parts.
https://w w w .tutorialspoint.com/java/java_url_processing.htm 1/12
Page 2 of 12
public URL(String protocol, String host, String file) throws
MalformedURLException
2
Identical to the previous constructor, except that the default port for the given
protocol is used.
public URL(String url) throws MalformedURLException
3
Creates a URL from the given String.
public URL(URL context, String url) throws MalformedURLException
4
Creates a URL by parsing together the URL and String arguments.
The URL class contains many methods for accessing the various parts of the URL being
represented. Some of the methods in the URL class include the following −
Sr.No. Method & Description
public equals(Object obj)
1
This method compares this URL for equality with another object.
public String getAuthority()
2
This method returns the authority of the URL.
public Object getContent()
3
This method returns the contents of this URL.
public Object getContent(Class<?>[] classes)
4
This method returns the contents of this URL.
public int getDefaultPort()
5
This method returns the default port for the protocol of the URL.
public String getFile()
6
This method returns the filename of the URL.
public String getHost()
7
This method returns the host of the URL.
public String getPath()
8
This method returns the path of the URL.
public int getPort()
9
This method returns the port of the URL.
public String getProtocol()
10
This method returns the protocol of the URL.
https://w w w .tutorialspoint.com/java/java_url_processing.htm 2/12
Page 3 of 12
public String getQuery()
11
This method returns the query part of the URL.
public String getRef()
12
This method returns the reference part of the URL.
public String getUserInfo()
13
This method returns the userInfo part of the URL.
public int hashCode()
14
This method creates and return an integer suitable for hash table indexing.
public URLConnection openConnection()
15 This method returns a URLConnection instance that represents a connection to
the remote object referred to by the URL.
public URLConnection openConnection(Proxy proxy)
This method acts as openConnection(), except that the connection will be
16
made through the specified proxy; Protocol handlers that do not support
proxing will ignore the proxy parameter and make a normal connection.
public InputStream openStream()
17 This method opens a connection to this URL and returns an InputStream for
reading from that connection.
public boolean sameFile(URL other)
18
This method compares two URLs, excluding the fragment component.
public static void
19 setURLStreamHandlerFactory(URLStreamHandlerFactory fac)
This method sets an application's URLStreamHandlerFactory.
public String toExternalForm()
20
This method constructs and return a string representation of this URL.
public String toString()
21
This method constructs and return a string representation of this URL.
public String toURI()
22
This method returns a URI equivalent to this URL.
Advertisement
https://w w w .tutorialspoint.com/java/java_url_processing.htm 3/12
Page 4 of 12
Example
The following URLDemo program demonstrates the various parts of a URL. A URL is
entered on the command line, and the URLDemo program outputs each part of the given
URL.
// File Name : URLDemo.java
import java.io.IOException;
import java.net.URL;
public class URLDemo {
public static void main(String [] args) {
try {
URL url = new URL("https://www.tutorialspoint.com/index.htm?
language=en#j2se");
System.out.println("URL is " + url.toString());
System.out.println("protocol is " + url.getProtocol());
System.out.println("authority is " + url.getAuthority());
System.out.println("file name is " + url.getFile());
System.out.println("host is " + url.getHost());
System.out.println("path is " + url.getPath());
System.out.println("port is " + url.getPort());
System.out.println("default port is " + url.getDefaultPort());
System.out.println("query is " + url.getQuery());
System.out.println("ref is " + url.getRef());
} catch (IOException e) {
e.printStackTrace();
}
https://w w w .tutorialspoint.com/java/java_url_processing.htm 4/12
Page 5 of 12
}
}
A sample run of the this program will produce the following result −
Output
URL is https://www.tutorialspoint.com/index.htm?language=en#j2se
protocol is https
authority is www.tutorialspoint.com
file name is /index.htm?language=en
host is www.tutorialspoint.com
path is /index.htm
port is -1
default port is 443
query is language=en
ref is j2se
URLConnections Class Methods
The openConnection() method returns a java.net.URLConnection, an abstract class
whose subclasses represent the various types of URL connections.
For example −
If you connect to a URL whose protocol is HTTP, the openConnection() method
returns an HttpURLConnection object.
If you connect to a URL that represents a JAR file, the openConnection() method
returns a JarURLConnection object, etc.
The URLConnection class has many methods for setting or determining information about
the connection, including the following −
Sr.No. Method & Description
void addRequestProperty(String key, String value)
1
Adds a general request property specified by a key-value pair.
boolean getAllowUserInteraction()
2
Returns the value of the allowUserInteraction field for this object.
https://w w w .tutorialspoint.com/java/java_url_processing.htm 5/12
Page 6 of 12
int getConnectTimeout()
3
Returns setting for connect timeout.
Object getContent()
4
Retrieves the contents of this URL connection.
Object getContent(Class[] classes)
5
Retrieves the contents of this URL connection.
String getContentEncoding()
6
Returns the value of the content-encoding header field.
int getContentLength()
7
Returns the value of the content-length header field.
long getContentLengthLong()
8
Returns the value of the content-length header field as long.
String getContentType()
9
Returns the value of the content-type header field.
long getDate()
10
Returns the value of the date header field.
static boolean getDefaultAllowUserInteraction()
11
Returns the default value of the allowUserInteraction field.
boolean getDefaultUseCaches()
12
Returns the default value of a URLConnection's useCaches flag.
static boolean getDefaultUseCaches(String protocol)
13
Returns the default value of the useCaches flag for the given protocol.
boolean getDoInput()
14
Returns the value of this URLConnection's doInput flag.
boolean getDoOutput()
15
Returns the value of this URLConnection's doOutput flag.
long getExpiration()
16
Returns the value of the expires header field.
static FileNameMap getFileNameMap()
17
Loads filename map (a mimetable) from a data file.
String getHeaderField(int n)
18
Returns the value for the nth header field.
https://w w w .tutorialspoint.com/java/java_url_processing.htm 6/12
Page 7 of 12
String getHeaderField(String name)
19
Returns the value of the named header field.
long getHeaderFieldDate(String name, long Default)
20
Returns the value of the named field parsed as date.
int getHeaderFieldInt(String name, int Default)
21
Returns the value of the named field parsed as a number.
String getHeaderFieldKey(int n)
22
Returns the key for the nth header field.
long getHeaderFieldLong(String name, long Default)
23
Returns the value of the named field parsed as a number.
Map<String,List<String>> getHeaderFields()
24
Returns an unmodifiable Map of the header fields.
long getIfModifiedSince()
25
Returns the value of this object's ifModifiedSince field.
InputStream getInputStream()
26
Returns an input stream that reads from this open connection.
int getLastModified()
27
Returns the value of the last-modified header field.
OutputStream getOutputStream()
28
Returns an output stream that writes to this connection.
Permission getPermission()
29 Returns a permission object representing the permission necessary to make
the connection represented by this object.
int getReadTimeout()
30 Returns setting for read timeout. 0 return implies that the option is disabled
(i.e., timeout of infinity).
Map<String,List<String>> getRequestProperties()
31
Returns an unmodifiable Map of general request properties for this connection.
String getRequestProperty(String key)
32
Returns the value of the named general request property for this connection.
URL getURL()
33
Returns the value of this URLConnection's URL field.
https://w w w .tutorialspoint.com/java/java_url_processing.htm 7/12
Page 8 of 12
boolean getUseCaches()
34
Returns the value of this URLConnection's useCaches field.
static String guessContentTypeFromName(String fname)
35 Tries to determine the content type of an object, based on the specified "file"
component of a URL.
static String guessContentTypeFromStream(InputStream is)
36 Tries to determine the type of an input stream based on the characters at the
beginning of the input stream.
void setAllowUserInteraction(boolean allowuserinteraction)
37
Set the value of the allowUserInteraction field of this URLConnection.
void setConnectTimeout(int timeout)
38 Sets a specified timeout value, in milliseconds, to be used when opening a
communications link to the resource referenced by this URLConnection.
static void setContentHandlerFactory(ContentHandlerFactory fac)
39
Sets the ContentHandlerFactory of an application.
static void setDefaultAllowUserInteraction(boolean
defaultallowuserinteraction)
40
Sets the default value of the allowUserInteraction field for all future
URLConnection objects to the specified value.
void setDefaultUseCaches(boolean defaultusecaches)
41
Sets the default value of the useCaches field to the specified value.
static void setDefaultUseCaches(String protocol, boolean defaultVal)
42 Sets the default value of the useCaches field for the named protocol to the
given value.
void setDoInput(boolean doinput)
43 Sets the value of the doInput field for this URLConnection to the specified
value.
void setDoOutput(boolean dooutput)
44 Sets the value of the doOutput field for this URLConnection to the specified
value.
static void setFileNameMap(FileNameMap map)
45
Sets the FileNameMap.
void setIfModifiedSince(long ifmodifiedsince)
46 Sets the value of the ifModifiedSince field of this URLConnection to the specified
value.
https://w w w .tutorialspoint.com/java/java_url_processing.htm 8/12
Page 9 of 12
void setReadTimeout(int timeout)
47
Sets the read timeout to a specified timeout, in milliseconds.
void setRequestProperty(String key, String value)
48
Sets the general request property.
void setUseCaches(boolean usecaches)
49 Sets the value of the useCaches field of this URLConnection to the specified
value.
String toString()
50
Returns a String representation of this URL connection.
Example
The following URLConnectionDemo program connects to a URL entered from the
command line.
If the URL represents an HTTP resource, the connection is cast to HttpURLConnection, and
the data in the resource is read one line at a time.
package com.tutorialspoint;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
public class URLConnDemo {
public static void main(String [] args) {
try {
URL url = new URL("https://www.tutorialspoint.com");
URLConnection urlConnection = url.openConnection();
HttpURLConnection connection = null;
if(urlConnection instanceof HttpURLConnection) {
connection = (HttpURLConnection) urlConnection;
}else {
System.out.println("Please enter an HTTP URL.");
return;
}
https://w w w .tutorialspoint.com/java/java_url_processing.htm 9/12
Page 10 of 12
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();
}
}
}
A sample run of this program will produce the following result −
Output
$ java URLConnDemo
.....a complete HTML content of home page of tutorialspoint.com.....
TOP TUTORIALS
Python Tutorial
Java Tutorial
C++ Tutorial
C Programming Tutorial
C# Tutorial
PHP Tutorial
R Tutorial
HTML Tutorial
CSS Tutorial
JavaScript Tutorial
SQL Tutorial
https://w w w .tutorialspoint.com/java/java_url_processing.htm 10/12
Page 11 of 12
TRENDING TECHNOLOGIES
Cloud Computing Tutorial
Amazon Web Services Tutorial
Microsoft Azure Tutorial
Git Tutorial
Ethical Hacking Tutorial
Docker Tutorial
Kubernetes Tutorial
DSA Tutorial
Spring Boot Tutorial
SDLC Tutorial
Unix Tutorial
CERTIFICATIONS
Business Analytics Certification
Java & Spring Boot Advanced Certification
Data Science Advanced Certification
Cloud Computing And DevOps
Advanced Certification In Business Analytics
Artificial Intelligence And Machine Learning
DevOps Certification
Game Development Certification
Front-End Developer Certification
AWS Certification Training
Python Programming Certification
COMPILERS & EDITORS
Online Java Compiler
Online Python Compiler
Online Go Compiler
Online C Compiler
Online C++ Compiler
Online C# Compiler
Online PHP Compiler
Online MATLAB Compiler
Online Bash Terminal
https://w w w .tutorialspoint.com/java/java_url_processing.htm 11/12
Page 12 of 12
Online SQL Compiler
Online Html Editor
ABOUT US | OUR TEAM | CAREERS | JOBS | CONTACT US | TERMS OF USE |
PRIVACY POLICY | REFUND POLICY | COOKIES POLICY | FAQ'S
Tutorials Point is a leading Ed Tech company striving to provide the best learning material on
technical and non-technical subjects.
© Copyright 2025. All Rights Reserved.
https://w w w .tutorialspoint.com/java/java_url_processing.htm 12/12