Java URL Resolve resolve(URL base, String relUrl)

Here you can find the source of resolve(URL base, String relUrl)

Description

Create a new absolute URL, from a provided existing absolute URL and a relative URL component.

License

Apache License

Parameter

Parameter Description
base the existing absolulte base URL
relUrl the relative URL to resolve. (If it's already absolute, it will be returned)

Exception

Parameter Description
MalformedURLException if an error occurred generating the URL

Return

the resolved absolute URL

Declaration

public static URL resolve(URL base, String relUrl) throws MalformedURLException 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.net.MalformedURLException;
import java.net.URL;

public class Main {
    /**/*from  ww  w.j a v a 2s.  c o m*/
     * Create a new absolute URL, from a provided existing absolute URL and a relative URL component.
     * @param base the existing absolulte base URL
     * @param relUrl the relative URL to resolve. (If it's already absolute, it will be returned)
     * @return the resolved absolute URL
     * @throws MalformedURLException if an error occurred generating the URL
     */
    public static URL resolve(URL base, String relUrl) throws MalformedURLException {
        // workaround: java resolves '//path/file + ?foo' to '//path/?foo', not '//path/file?foo' as desired
        if (relUrl.startsWith("?"))
            relUrl = base.getPath() + relUrl;
        // workaround: //example.com + ./foo = //example.com/./foo, not //example.com/foo
        if (relUrl.indexOf('.') == 0 && base.getFile().indexOf('/') != 0) {
            base = new URL(base.getProtocol(), base.getHost(), base.getPort(), "/" + base.getFile());
        }
        return new URL(base, relUrl);
    }

    /**
     * Create a new absolute URL, from a provided existing absolute URL and a relative URL component.
     * @param baseUrl the existing absolute base URL
     * @param relUrl the relative URL to resolve. (If it's already absolute, it will be returned)
     * @return an absolute URL if one was able to be generated, or the empty string if not
     */
    public static String resolve(final String baseUrl, final String relUrl) {
        URL base;
        try {
            try {
                base = new URL(baseUrl);
            } catch (MalformedURLException e) {
                // the base is unsuitable, but the attribute/rel may be abs on its own, so try that
                URL abs = new URL(relUrl);
                return abs.toExternalForm();
            }
            return resolve(base, relUrl).toExternalForm();
        } catch (MalformedURLException e) {
            return "";
        }

    }
}

Related

  1. resolve(final URL url)
  2. resolve(URL base, String uri)
  3. resolveGoogleRedirect(String url)
  4. resolveHref(String baseUrl, String href)
  5. resolveManifestResources(final URL manifestUrl, final List resources)