URL Components

In this chapter you will learn:

  1. How to get URL components in Java

Get URL component

You can retrieve the various components of a URL object by using these methods:

public java.lang.String getFile ()
public java.lang.String getHost ()
public java.lang.String getPath ()
public int getPort ()
public java.lang.String getProtocol ()
public java.lang.String getQuery ()

The following code shows how to use the methods above.

import java.net.URL;
//from  j ava2  s  .  c  om
public class Main {
  public static void main(String[] args) throws Exception {
    URL url = new URL("http://www.java2s.com:80/en/index.html?name=demo#first");
    System.out.println("protocol:" + url.getProtocol());
    System.out.println("prot:" + url.getPort());
    System.out.println("host:" + url.getHost());
    System.out.println("path:" + url.getPath());
    System.out.println("file:" + url.getFile());
    System.out.println("query:" + url.getQuery());
    System.out.println("ref:" + url.getRef());
  }
}

The code above generates the following result.

Next chapter...

What you will learn in the next chapter:

  1. How to convert file path to URL
Home » Java Tutorial » URL URI
URL
URL Creation
URL for jar file
URL Components
Convert file path to URL
URL Relative
URL Protocol
Read from URL
Compare URL
URLConnection
HTTP Header
URLConnection Post
Cookie
URLConnection Read
HttpURLConnection
HttpURLConnection Properties
HttpURLConnection proxy
HttpURLConnection Authenticator
HTTPS
JarURLConnection
Encode a URL
Decode a URL
URI
URI Normalization
URI Resolution
URI Relativization
Convert URI to URL
IP Address
IP Ping
NetworkInterface