Created
September 19, 2017 15:58
-
-
Save trenthudy/3feac5bfdf9765c2729126fd8c3103bb to your computer and use it in GitHub Desktop.
This file contains 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
/** | |
* Created by trent on 9/18/17. | |
*/ | |
public class HelloWorldGist { | |
/** | |
* Concatenate a URL and an endpoint. | |
* | |
* In some cases, a base URL ends with '/' and an endpoint starts with '/', so | |
* simply adding them will return an invalid URL: | |
* | |
* 'mydomain.com/' + '/user/12345' = 'mydomain.com//user/12345' | |
* | |
* Other times, neither the base URL end with '/' nor the endpoint starts with '/'. | |
* Again, we get an invalid URL: | |
* | |
* 'mydomain.com' + 'user/12345' = 'mydomain.comuser/12345' | |
* | |
* This is a simple way to get a properly formatted URL every time. | |
* | |
* NOTE: If a null or empty string is passed to this method, null will be returned. | |
* | |
* @param baseURL The base URL | |
* @param endpoint The endpoint | |
* @return String - The concatenation of the base URL and the endpoint. | |
*/ | |
public static String createUrl(String baseURL, String endpoint) { | |
if (baseURL == null || baseURL.isEmpty() || endpoint == null || endpoint.isEmpty()) { | |
return null; | |
} | |
if (baseURL.endsWith("/") && endpoint.startsWith("/")) { | |
return baseURL.substring(0, baseURL.length() - 1) + endpoint; | |
} | |
if (!baseURL.endsWith("/") && !endpoint.startsWith("/")) { | |
return baseURL + "/" + endpoint; | |
} | |
return baseURL + endpoint; | |
} | |
public static void main(String[] args) { | |
// All return a proper URL ('mydomain.com/login'). | |
createUrl("mydomain.com/", "/login"); | |
createUrl("mydomain.com", "/login"); | |
createUrl("mydomain.com/", "login"); | |
createUrl("mydomain.com", "login"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment