How to Validate a URL in Java

Cloudmersive
2 min readFeb 2, 2021

When creating a plan to prevent and identify cyberattacks, it’s important to ensure all bases are covered as threats can enter your system via various avenues. One such avenue is through URLs. An invalid URL can occasionally indicate a hidden threat, which is why checking the validity can be a crucial action to maintain the security of your users and your business. The following API will validate whether the URL is syntactically valid, whether it exists, and whether the endpoint is virus-free.

To begin, we are going to install the SDK with Maven or Gradle. To install with Maven, add a reference to the repository in pom.xml:

<repositories>
<repository>
<id>jitpack.io</id>
<url>https://jitpack.io</url>
</repository>
</repositories>

Then, add a reference to the dependency:

<dependencies>
<dependency>
<groupId>com.github.Cloudmersive</groupId>
<artifactId>Cloudmersive.APIClient.Java</artifactId>
<version>v3.54</version>
</dependency>
</dependencies>

Or, to install with Gradle, add the following in your root build.gradle:

allprojects {
repositories {
...
maven { url 'https://jitpack.io' }
}
}

And add the dependency in the build.gradle:

dependencies {
implementation 'com.github.Cloudmersive:Cloudmersive.APIClient.Java:v3.54'
}

Once we have installed the package, we’re ready to call the Validate URL function with the following code:

// Import classes:
//import com.cloudmersive.client.invoker.ApiClient;
//import com.cloudmersive.client.invoker.ApiException;
//import com.cloudmersive.client.invoker.Configuration;
//import com.cloudmersive.client.invoker.auth.*;
//import com.cloudmersive.client.DomainApi;
ApiClient defaultClient = Configuration.getDefaultApiClient();// Configure API key authorization: Apikey
ApiKeyAuth Apikey = (ApiKeyAuth) defaultClient.getAuthentication("Apikey");
Apikey.setApiKey("YOUR API KEY");
// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)
//Apikey.setApiKeyPrefix("Token");
DomainApi apiInstance = new DomainApi();
ValidateUrlRequestFull request = new ValidateUrlRequestFull(); // ValidateUrlRequestFull | Input URL request
try {
ValidateUrlResponseFull result = apiInstance.domainUrlFull(request);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling DomainApi#domainUrlFull");
e.printStackTrace();
}

The returned result will provide a well-formed URL, in addition to indicating the validity of your syntax, domain, and endpoint. To retrieve your API key, simply head to the Cloudmersive website and register for a free account; this will give you access to 800 monthly calls over this and our many other APIs.

--

--

Cloudmersive

There’s an API for that. Cloudmersive is a leader in Highly Scalable Cloud APIs.