Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Java URL Class

Java URL Class

URL (Uniform Resource Locator) is used to locate resources on the Internet. In Java, thejava.net.URL class provides URL handling capabilities, allowing developers to create URL objects, parse URL components, and establish network connections.


Basic Structure of the URL Class

A standard URL usually consists of the following parts:

protocol://host:port/path?query#fragment

For example:

https://www.example.com:8080/products?id=123#details

Main Components

  1. Protocol:https
  2. Host:www.example.com
  3. Port:8080
  4. Path:/products
  5. Query Parameters:id=123
  6. Fragment:details

Creating URL Objects

Java provides several constructors to create URL objects:

1. Using a Complete URL String

Example

try

{

   

URL

url

=

new

URL

(

"https://www.example.com"

)

;

}

catch

(

MalformedURLException

e

)

{

    e.

printStackTrace

(

)

;

}

2. Specifying Protocol, Host, and File Separately

Example

try

{

   

URL

url

=

new

URL

(

"https"

,

"www.example.com"

,

"/index.html"

)

;

}

catch

(

MalformedURLException

e

)

{

    e.

printStackTrace

(

)

;

}

3. Specifying Protocol, Host, Port, and File

Example

try

{

   

URL

url

=

new

URL

(

"https"

,

"www.example.com"

,

8080

,

"/api/data"

)

;

}

catch

(

MalformedURLException

e

)

{

    e.

printStackTrace

(

)

;

}


Common Methods of the URL Class

Getting Information About URL Parts

Example

URL

url

=

new

URL

(

"https://www.example.com:8080/products?id=123#details"

)

;

System

.

out

.

println

(

"Protocol: "

url.

getProtocol

(

)

)

;

 

// https

System

.

out

.

println

(

"Host: "

url.

getHost

(

)

)

;

     

// www.example.com

System

.

out

.

println

(

"Port: "

url.

getPort

(

)

)

;

     

// 8080

System

.

out

.

println

(

"Path: "

url.

getPath

(

)

)

;

     

// /products

System

.

out

.

println

(

"Query: "

url.

getQuery

(

)

)

;

   

// id=123

System

.

out

.

println

(

"Fragment: "

url.

getRef

(

)

)

;

     

// details

Opening Network Connections

The URL class provides several methods to open network connections:

  1. openConnection(): Returns a URLConnection object
  2. openStream(): Opens an input stream for reading data

Example

// Use openStream() to read web page content

try

(

InputStream

in

=

url.

openStream

(

)

;

     

BufferedReader

reader

=

new

BufferedReader

(

new

InputStreamReader

(

in

)

)

)

{

   

String

line

;

   

while

(

(

line

=

reader.

readLine

(

)

)

!=

null

)

{

       

System

.

out

.

println

(

line

)

;

   

}

}

catch

(

IOException

e

)

{

    e.

printStackTrace

(

)

;

}


URL Encoding and Decoding

In a URL, some characters need to be encoded (such as spaces, Chinese characters, etc.). Java provides the URLEncoder and URLDecoder classes to handle encoding and decoding.

URL Encoding Example

Example

String

query

=

"name=John&age=25"

;

String

encodedQuery

=

URLEncoder

.

encode

(

query,

"UTF-8"

)

;

System

.

out

.

println

(

encodedQuery

)

;

 

// Output: name%3DJohn%26age%3D25

URL Decoding Example

Example

String

decodedQuery

=

URLDecoder

.

decode

(

encodedQuery,

"UTF-8"

)

;

System

.

out

.

println

(

decodedQuery

)

;

 

// Output: name=John&age=25


Practical Application Examples

Example 1: Downloading a File

Example

URL

fileUrl

=

new

URL

(

"https://example.com/files/sample.pdf"

)

;

try

(

InputStream

in

=

fileUrl.

openStream

(

)

;

     

FileOutputStream

out

=

new

FileOutputStream

(

"sample.pdf"

)

)

{

   

byte

[

]

buffer

=

new

byte

[

1024

]

;

   

int

bytesRead

;

   

while

(

(

bytesRead

=

in.

read

(

buffer

)

)

!=

1

)

{

        out.

write

(

buffer,

0

, bytesRead

)

;

   

}

   

System

.

out

.

println

(

"File download complete"

)

;

}

catch

(

IOException

e

)

{

    e.

printStackTrace

(

)

;

}

Example 2: Calling a REST API

Example

URL

apiUrl

=

new

URL

(

"https://api.example.com/data?param1=value1"

)

;

try

(

BufferedReader

reader

=

new

BufferedReader

(

       

new

InputStreamReader

(

apiUrl.

openStream

(

)

)

)

)

{

    StringBuilder response

=

new

StringBuilder

(

)

;

   

String

line

;

   

while

(

(

line

=

reader.

readLine

(

)

)

!=

null

)

{

        response.

append

(

line

)

;

   

}

   

System

.

out

.

println

(

"API response: "

response.

toString

(

)

)

;

}

catch

(

IOException

e

)

{

    e.

printStackTrace

(

)

;

}


Notes

  1. Exception handling: URL constructors may throw MalformedURLException, and network operations may throw IOException
  2. Safety: Avoid constructing URLs from untrusted sources
  3. Performance: For frequent network requests, consider using a connection pool
  4. Encoding: Ensure URL encoding is handled correctly, especially when non-ASCII characters are involved