Skip to content

Instantly share code, notes, and snippets.

@dariahervieux
Last active October 20, 2020 15:25
Show Gist options
  • Save dariahervieux/af19530c222df02205366d8f2603d0d5 to your computer and use it in GitHub Desktop.
Save dariahervieux/af19530c222df02205366d8f2603d0d5 to your computer and use it in GitHub Desktop.
Creating URL from strings: absolute and realtive URLS
import java.net.URL;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.MalformedURLException;
public class URLCreator {
public static void main(String[ ] args) throws MalformedURLException, URISyntaxException {
//base URL
URL urlPlateform = new URL("http://somehost.com/context");
//relative URL we want to add to the base URL
//since it's impossible to create 'relative' URL, we create URI to be able to verify it
URI uriRelative = new URI("relative");
//complete URL created as URI
URI uriComplete = new URI("http://somehost.com/relative");
//when URI to add to the base URL is relative, the result is a valid URL concatenating base URL ans relaive URL
System.out.println(creerURL(uriRelative, urlPlateform).toString());
//when URI to add to the base URL is absolute, the result is a valid URL created from the abolute URI (ignoring base URL)
System.out.println(creerURL(uriComplete, urlPlateform).toString());
}
public static URL creerURL(URI uri, URL baseURL) throws MalformedURLException {
if (!uri.isAbsolute()) {
String nouveauURL = baseURL.toString() + "/" + uri.getPath();
return new URL(nouveauURL);
// return new URL(baseURL, (baseURL.getPath() + "/" + uri.getPath()));
}
return uri.toURL();
}
public static URL creerURLv2(URI uri, URL baseURL) throws MalformedURLException {
if (!uri.isAbsolute()) {
return new URL(baseURL, (baseURL.getPath() + "/" + uri.getPath()));
}
return uri.toURL();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment