Created
March 12, 2025 16:39
-
-
Save darragh-murphy/39a02926be8bd7ba1c482ef7037258f7 to your computer and use it in GitHub Desktop.
URLBuilder
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public class URLBuilder { | |
| public static String buildUrl(String baseUrl, Map<String, String> params) { | |
| if (params == null || params.isEmpty()) { | |
| return baseUrl; | |
| } | |
| String queryString = params.entrySet().stream() | |
| .map(entry -> String.format("%s=%s", | |
| URLEncoder.encode(entry.getKey(), StandardCharsets.UTF_8), | |
| URLEncoder.encode(entry.getValue(), StandardCharsets.UTF_8))) | |
| .collect(Collectors.joining("&")); | |
| return baseUrl + "?" + queryString; | |
| } | |
| public static void main(String[] args) { | |
| Map<String, String> params = Map.of( | |
| "search", "java encoding", | |
| "page", "1", | |
| "sort", "desc" | |
| ); | |
| String url = buildUrl("https://example.com/api", params); | |
| System.out.println(url); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment