Stop treating URLs as strings!

Kumar Chetan Sharma
2 min readMay 1, 2024

tl;dr — Regardless of programming language, treat URLs as first class citizens or objects

Now the longer version.

If you look at a URL, it is a string. Hence, the common sense tells you to just find the question mark and divide the string to find query parameters from URL.

const URL = "https://www.google.com/search?q=Is this correct?&let=me ask you again&are=you sure?";
const queryParametersString = URL.split("?");
const queryParameters = queryParametersString[1];
console.log(queryParameters); // 'q=Is this correct'

Or in Java

String URL = "https://www.google.com/search?q=Is this correct?&let=me ask you again&are=you sure?";
// Splitting the URL string to separate the query parameters
String[] queryParametersString = URL.split("\\?");
// Extracting the query parameters
String queryParameters = queryParametersString.length > 1 ? queryParametersString[1] : "";
// Printing the query parameters
System.out.println(queryParameters);

You might have seen variation of this in your favorite or hated programming language. This is just the tip of code icebergs I have seen.

What most of the developers miss out is that URLs can represent state. And they are not always made up of ASCII characters. URLs can have UTF-8 or UTF-16 characters. Or are not always pointing to http protocol

const ohShit = "https://www.google.com/search?q=💩";
const habibi = "https://www.google.com/search?q=!حبيبي"
const exampleFTPURL = "ftp://example.com/path/to/some/file.txt";
const emailMe = "mailto:user@example.com?subject=MessageTitle&body=Message Content";

Manipulating these URLs as string introduce bugs one can avoid. All of the programming languages provide ways to manage URLs using either build in function and APIs or through sphisticated libraries.

import okhttp3.HttpUrl; //Import okHttp or Apache http client libs

// boiler plate ...

String URL = "https://www.google.com/search?q=Is this correct?&let=me ask you again&are=you sure?";
// Parsing the URL with OkHttp
HttpUrl httpUrl = HttpUrl.parse(URL);

if (httpUrl != null) {
// Extracting the query parameters
String queryParameters = httpUrl.query();
// Printing the query parameters
System.out.println(queryParameters);
} else {
System.out.println("Invalid URL format");
}

Or

const exampleURL = new URL("https://www.google.com/search?q=Is this correct?&let=me ask you again&are=you sure?");
console.log(exampleURL.search); //'?q=Is%20this%20correct?&let=me%20ask%20you%20again&are=you%20sure?'
exampleURL.searchParams.keys().forEach(k => console.log(`${k}=${exampleURL.searchParams.get(k)}`));

In all the patterns I have seen, most are around constructing URLs.

    const res = await fetch(`/api/common?baseUrl=${baseUrl}&${encodeURI(`data=${data}`)}`)

The above example is from a production branch of an application. In case of JavaScript one can use URL interface. Here is an example

const baseURL = 'https://jsonplaceholder.typicode.com/';
const apiURL = new URL(`comments`, baseURL);
apiURL.searchParams.set('postId', '1');
const response = await axios.get(apiURL.toString());

Or in Java you can use okhttp or Apache http client

import org.apache.http.client.utils.URIBuilder;
import java.net.URI;
import java.net.URISyntaxException;

//boilerplate

try {
URIBuilder uriBuilder = new URIBuilder('https://jsonplaceholder.typicode.com/comments')
.addParameter('postId', '1');
URI uri = uriBuilder.build();
String constructedUrl = uri.toString();
System.out.println("Constructed URL: " + constructedUrl);
} catch (URISyntaxException e) {
System.err.println("Error constructing URL: " + e.getMessage());
}

These libraries take care of constructing the URL, encoding query params and everything else you need with URLs. Do you have to write few extra line of code? Yes! And it is worth. No one wants to fix bugs on Friday evening.

Happy coding!

--

--

Kumar Chetan Sharma

C0d3🐵 from 🇮🇳. selfTaught. 😨 of CS, Algos & DS. World famous 👨‍🍳 at home. Pro Level Pro-Crastinator. Man child. Dad of (✿◠‿◠)(◠‿◠✿)