Start learning free

LESSON 2 OF 173 · BACKEND: HOW THE WEB WORKS

The Parts of a URL in Java

Practice

A URL is the full address of something on the web. It is made of parts, and each part answers its own question: the scheme (how to talk to the server), the host (which computer), the port (which server on that computer), the path (what you want) and the query string (with which options, after the ?).

The class URI, from java.net, splits a URL into those parts: URI.create(...) makes one, and a method gives each part. Here it is on another URL:

URI site = URI.create("https://algocademy.com/blog?page=2");
System.out.println(site.getHost());    // algocademy.com
System.out.println(site.getPort());    // -1: no port is written
System.out.println(site.getQuery());   // page=2

Scheme, host and port tell your program where to send the request. The path and the query travel inside the request and tell the server what you want. When a URL writes no port, the client uses 80 for http and 443 for https.

The starting code builds url for the supplier's cheap products and prints it. Your finished program must print:

URL: http://127.0.0.1:8001/prices?max_price=5
Scheme: http
Host: 127.0.0.1
Port: 8001
Path: /prices
Query: max_price=5

Your task: split url with URI.create and keep the result in parts, then print its scheme, host, port, path and query, each after its label.


Assignment
Follow the Coding Tutorial to split the supplier's URL into its five parts and print each one.


Hint
Each part comes from a method of the result: getScheme(), getHost(), getPort(), getPath() and getQuery(). Join each label and its part with +.


STEP 1 OF 5
    Ctrl + Enter to check

    Web Url Parts in Java

    Keep going with Java1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free