java.net.URL doc can help you figure out how to "Extract base url from full URL"
Preliminary Note:
You should pay attention to this important note on the javadoc URL page :
"Note that in certain cases, the URI class escapes its component fields. The recommended way to control the encoding and decryption of URLs is to use URIs and convert between the two classes using toURI () and URI.toURL () ."
Self-evident unit tests:
Here are two simple test cases illustrating the concept of basic Url.
package com.elementique.web; import org.junit.Test; import java.net.URI; import java.net.URL; import static org.junit.Assert.assertEquals; public class UrlTest { @Test public void baseUrlAuthority() throws Exception { URL url = URI.create("http://username: password@host1 :8080/directory/file?query#ref").toURL(); assertEquals("http", url.getProtocol());
Extract base URL:
So, "fetching the base url from the full URL" can be done as follows:
return url.getProtocol()+"://"+url.getAuthority()+"/"
Or this if you do NOT want the username / password part
if(url.getPort() == -1){ // port is not return url.getProtocol()+"://"+url.getHost()+"/"; } else { return url.getProtocol()+"://"+url.getHost()+":"+url.getPort()"/"; }
Implementation:
Here is an implementation that does this (based on getAuthority ()):
public static String getBaseUrl(String urlString) { if(urlString == null) { return null; } try { URL url = URI.create(urlString).toURL(); return url.getProtocol() + "://" + url.getAuthority() + "/"; } catch (Exception e) { return null; } }
Remarks:
Delete the trailing "/", you do not want it
source share