eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – LJB – NPI EA (cat = Core Java)
announcement - icon

Code your way through and build up a solid, practical foundation of Java:

>> Learn Java Basics

Partner – LambdaTest – NPI EA (cat= Testing)
announcement - icon

Distributed systems often come with complex challenges such as service-to-service communication, state management, asynchronous messaging, security, and more.

Dapr (Distributed Application Runtime) provides a set of APIs and building blocks to address these challenges, abstracting away infrastructure so we can focus on business logic.

In this tutorial, we'll focus on Dapr's pub/sub API for message brokering. Using its Spring Boot integration, we'll simplify the creation of a loosely coupled, portable, and easily testable pub/sub messaging system:

>> Flexible Pub/Sub Messaging With Spring Boot and Dapr

1. Overview

In this article, we are going to explore low-level operations with Java network programming. We’ll be taking a deeper look at URLs.

A URL is a reference or an address to a resource on the network. And simply put, Java code communicating over the network can use the java.net.URL class to represent the addresses of resources.

The Java platform ships with built-in networking support, bundled up in the java.net package:

import java.net.*;

2. Creating a URL

Starting from Java version 20, all the constructors of the java.net.URL have been deprecated, so we will use java.net.URI constructors instead.

Let’s first create a URL object by using URI.toURL(). We create a URI by passing in a String representing the human readable address of the resource then construct a URL from it:

URL home = new URI("http://baeldung.com/a-guide-to-java-sockets").toURL();

We’ve just created an absolute URL object. The address has all the parts required to reach the desired resource.

We can also create a relative URI object; It is however important to note that the toURL() method prevents the creation of URLs if the URI is not absolute as shown in this test:

@Test
    public void givenRelativeUrl_whenCreatesRelativeUrl_thenThrows() {
    URI uri = new URI("/a-guide-to-java-sockets");
    Assert.assertThrows(IllegalArgumentException.class, () -> uri.toURL());
}

There are other ways to create a URL by calling the available java.net.URI constructors which takes in the component parts of the URL string. We will cover this in the next section after covering URL components.

3. URL Components

A URL is made up of a few components – which we’ll explore in this section.

Let’s first look at the separation between the protocol identifier and the resource – these two components are separated by a colon followed by two forward slashes i.e. ://.

If we have a URL such as http://baeldung.com then the part before the separator, http, is the protocol identifier while the one that follows is the resource name, baeldung.com.

Let’s have a look at the API that the URI class exposes.

3.1. The Protocol

To retrieve the protocol – we use the getProtocol() method:

@Test
public void givenUrl_whenCanIdentifyProtocol_thenCorrect(){
    URL url = new URI("http://baeldung.com").toURL();
    
    assertEquals("http", url.getProtocol());
}

3.2. The Port

To get the port – we use the getPort() method:

@Test
public void givenUrl_whenGetsDefaultPort_thenCorrect(){
    URL url = new URI("http://baeldung.com").toURL();
    
    assertEquals(-1, url.getPort());
    assertEquals(80, url.getDefaultPort());
}

Note that this method retrieves the explicitly defined port. If no port is defined explicitly, it will return -1.

And because HTTP communication uses port 80 by default – no port is defined.

Here’s an example where we do have an explicitly defined port:

@Test
public void givenUrl_whenGetsPort_thenCorrect(){
    URL url = new URI("http://baeldung.com:8090").toURL();
    
    assertEquals(8090, url.getPort());
}

3.3. The Host

The host is the part of the resource name that starts right after the :// separator and ends with the domain name extension, in our case .com.

We call the getHost() method to retrieve the hostname:

@Test
public void givenUrl_whenCanGetHost_thenCorrect(){
    URL url = new URI("http://baeldung.com").toURL();
    
    assertEquals("baeldung.com", url.getHost());
}

3.4. The File Name

Whatever follows after the hostname in a URL is referred to as the file name of the resource. It can include both path and query parameters or just a file name:

@Test
public void givenUrl_whenCanGetFileName_thenCorrect1() {
    URL url = new URI("http://baeldung.com/guidelines.txt").toURL();
    
    assertEquals("/guidelines.txt", url.getFile());
}

Assuming Baeldung has java 8 articles under the URL /articles?topic=java&version=8. Everything after the hostname is the file name:

@Test
public void givenUrl_whenCanGetFileName_thenCorrect2() {
    URL url = new URI("http://baeldung.com/articles?topic=java&version=8").toURL();
    
    assertEquals("/articles?topic=java&version=8", url.getFile());
}

3.5. Path Parameters

We can also only inspect the path parameters which in our case is /articles:

@Test
public void givenUrl_whenCanGetPathParams_thenCorrect() {
    URL url = new URI("http://baeldung.com/articles?topic=java&version=8").toURL();
    
    assertEquals("/articles", url.getPath());
}

3.6. Query Parameters

Likewise, we can inspect the query parameters, which is topic=java&version=8:

@Test
public void givenUrl_whenCanGetQueryParams_thenCorrect() {
    URL url = new URI("http://baeldung.com/articles?topic=java&version=8").toURL();
    
    assertEquals("topic=java&version=8", url.getQuery());
}

4. Creating URL With Component Parts

Since we have now looked at the different URL components and their place in forming the complete address to the resource, we can look at another method of creating a URL object by passing in the component parts.

4.1. Using the URI() Constructors

One of the available constructors takes the protocol, the hostname, the file name, and the fragment respectively:

@Test
public void givenUrlComponents_whenConstructsCompleteUrl_thenCorrect() {
    String protocol = "http";
    String host = "baeldung.com";
    String file = "/guidelines.txt";
    String fragment = "myImage";
    URL url = new URI(protocol, host, file, fragment).toURL();
    assertEquals("http://baeldung.com/guidelines.txt#myImage", url.toString());
}

You can also use the constructor with the additional userInfo, port, and query:

@Test
public void givenUrlComponents_whenConstructsCompleteUrl_thenCorrect2() {
    String protocol = "http";
    String username = "admin";
    String host = "baeldung.com";
    String file = "/articles";
    String query = "topic=java&version=8";
    String fragment = "myImage";
    URL url = new URI(protocol, username, host, -1, file, query, fragment).toURL();
    assertEquals("http://[email protected]/articles?topic=java&version=8#myImage", url.toString());
}

4.2. Using Apache HttpClient’s URIBuilder

We’ve seen how to build a URL object using the standard URI() constructors. However, it could be error-prone when the URL contains many query parameters.

Some popular frameworks and libraries have provided nice URL builders to allow us to build a URL object easily.

First, let’s look at Apache HttpClient.

Apache HttpClient is a popular library to help us handle HTTP requests and responses. Further, it ships with a URIBuilder, which allows us to conveniently construct URL objects.

To use the URIBuilder class, we need first to add the Apache HttpClient dependency to our project:

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.14</version>
</dependency>

The latest version can be found here.

Using URIBuilder, we can easily set different URL components, such as port, path, parameters, and so on, and build the URL object:

@Test
public void givenUrlParameters_whenBuildUrlWithURIBuilder_thenSuccess() throws URISyntaxException, MalformedURLException {
    URIBuilder uriBuilder = new URIBuilder("http://baeldung.com/articles");
    uriBuilder.setPort(9090);
    uriBuilder.addParameter("topic", "java");
    uriBuilder.addParameter("version", "8");
    URL url = uriBuilder.build().toURL();
    assertEquals("http://baeldung.com:9090/articles?topic=java&version=8", url.toString());
}

As we can see in the test above, we can add parameters with URIBuilder‘s addParameter() method. Additionally, URIBuilder provides the addParameters() method, which allows us to add multiple parameters in one shot. It’s particularly useful when we’ve prepared all parameters in a special data structure, such as a Map:

@Test
public void givenUrlParametersInMap_whenBuildUrlWithURIBuilder_thenSuccess() 
  throws URISyntaxException, MalformedURLException {
    Map<String, String> paramMap = ImmutableMap.of("topic", "java", "version", "8");
    URIBuilder uriBuilder = new URIBuilder("http://baeldung.com/articles");
    uriBuilder.setPort(9090);
    uriBuilder.addParameters(paramMap.entrySet()
      .stream()
      .map(entry -> new BasicNameValuePair(entry.getKey(), entry.getValue()))
      .collect(toList()));
               
    URL url = uriBuilder.build().toURL();
    assertEquals("http://baeldung.com:9090/articles?topic=java&version=8", url.toString());
}

In the example above, we use the Java Stream API to convert the parameter Map to a list of BasicNameValuePair objects.

4.3. Using Spring-web’s UriComponentsBuilder

Spring is a widely used framework. Spring-web offers us UriComponentsBuilder, a nice class to build URL objects straightforwardly.

Again, first, we must make sure our project has included the spring-web dependency:

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-web</artifactId>
    <version>6.0.8</version>
</dependency>

We can find Spring-web’s latest version in the Maven central repository.

Finally, let’s build a URL object using UriComponentsBuilder:

@Test
public void givenUrlParameters_whenBuildUrlWithSpringUriComponentsBuilder_thenSuccess() 
  throws MalformedURLException {
    URL url = UriComponentsBuilder.newInstance()
      .scheme("http")
      .host("baeldung.com")
      .port(9090)
      .path("articles")
      .queryParam("topic", "java")
      .queryParam("version", "8")
      .build()
      .toUri()
      .toURL();
    
    assertEquals("http://baeldung.com:9090/articles?topic=java&version=8", url.toString());
}

5. Conclusion

In this article, we discussed the URL class and saw how to use it in Java to access network resources programmatically.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

eBook Jackson – NPI EA – 3 (cat = Jackson)