Here you can find the source of getUrl(URL base, String path)
Parameter | Description |
---|---|
base | An optional URL which is used with a relative path parameter. |
path | Either an absolute path or a relative path together with the base parameter. |
Parameter | Description |
---|---|
MalformedURLException | an exception |
public static URL getUrl(URL base, String path) throws MalformedURLException
//package com.java2s; // See LICENSE.txt for license information import java.net.MalformedURLException; import java.net.URL; public class Main { /**// w w w.j a v a2 s. c o m * Attempts to return a valid URL from either an absolute 'path' or a relative 'path' * combined with 'base'. * @param base An optional URL which is used with a relative path parameter. * @param path Either an absolute path or a relative path together with the base parameter. * @return A valid URL or {@code null} in case of an error. * @throws MalformedURLException */ public static URL getUrl(URL base, String path) throws MalformedURLException { URL retVal = null; if (path != null) { try { // try absolute url first retVal = new URL(path); } catch (MalformedURLException mue) { retVal = null; } if (retVal == null && base != null) { // try relative url String baseUrl = base.toExternalForm(); int idx = baseUrl.indexOf('?'); String basePath = (idx >= 0) ? baseUrl.substring(0, idx) : baseUrl; String suffix = (idx >= 0) ? baseUrl.substring(idx) : ""; if (basePath.contains(path)) { retVal = new URL(basePath + suffix); } else { int cnt = 0; if (basePath.charAt(basePath.length() - 1) == '/') { cnt++; } if (path.charAt(0) == '/') { cnt++; } if (cnt == 2) { path = path.substring(1); } else if (cnt == 0) { path = '/' + path; } retVal = new URL(basePath + path + suffix); } } } return retVal; } }