Java URL Resolve resolveHref(String baseUrl, String href)

Here you can find the source of resolveHref(String baseUrl, String href)

Description

This method takes an base url and resolves the href to an url

License

Open Source License

Parameter

Parameter Description
baseUrl a parameter
href a parameter

Exception

Parameter Description
MalformedURLException an exception

Return

string

Declaration

public static String resolveHref(String baseUrl, String href) throws MalformedURLException 

Method Source Code

//package com.java2s;
/**//w w  w  . ja  v a 2s . c o  m
 * aletheia
 * A browser like application to send raw http requests. It is designed for 
 * debugging and finding security issues in web applications. For the current 
 * version and more informations visit <http://code.google.com/p/aletheia>
 * 
 * Copyright (c) 2010-2015 Christoph Kappestein <k42b3.x@gmail.com>
 * 
 * This file is part of Aletheia. Aletheia is free software: you can 
 * redistribute it and/or modify it under the terms of the GNU 
 * General Public License as published by the Free Software Foundation, 
 * either version 3 of the License, or at any later version.
 * 
 * Aletheia is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with Aletheia. If not, see <http://www.gnu.org/licenses/>.
 */

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

import java.util.Stack;

public class Main {
    /**
     * This method takes an base url and resolves the href to an url
     * 
     * @param baseUrl
     * @param href
     * @return string
     * @throws MalformedURLException
     */
    public static String resolveHref(String baseUrl, String href) throws MalformedURLException {
        URL currentUrl = new URL(baseUrl);

        if (href.startsWith("http://") || href.startsWith("https://")) {
            // we have an absolute url
            return href;
        } else if (href.startsWith("//")) {
            return currentUrl.getProtocol() + ":" + href;
        } else if (href.startsWith("?")) {
            return currentUrl.getProtocol() + "://" + currentUrl.getHost() + currentUrl.getPath() + href;
        } else {
            // we have an path wich must be resolved to the base url
            String completePath;

            if (href.startsWith("/")) {
                completePath = href;
            } else {
                int pos = currentUrl.getPath().lastIndexOf('/');
                String path;

                if (pos != -1) {
                    path = currentUrl.getPath().substring(0, pos);
                } else {
                    path = currentUrl.getPath();
                }

                completePath = path + "/" + href;
            }

            // remove dot segments from path
            String path = removeDotSegments(completePath);

            // build url
            String url = currentUrl.getProtocol() + "://" + currentUrl.getHost() + path;

            // add query params
            int sPos, ePos;
            sPos = href.indexOf('?');

            if (sPos != -1) {
                String query;
                ePos = href.indexOf('#');

                if (ePos == -1) {
                    query = href.substring(sPos + 1);
                } else {
                    query = href.substring(sPos + 1, ePos);
                }

                if (!query.isEmpty()) {
                    url += "?" + query;
                }
            }

            // add fragment
            sPos = href.indexOf('#');

            if (sPos != -1) {
                String fragment = href.substring(sPos + 1);

                if (!fragment.isEmpty()) {
                    url += "#" + fragment;
                }
            }

            return url;
        }
    }

    public static String removeDotSegments(String relativePath) {
        // remove query or fragment part if any
        int pos = relativePath.indexOf('?');

        if (pos != -1) {
            relativePath = relativePath.substring(0, pos);
        }

        pos = relativePath.indexOf('#');

        if (pos != -1) {
            relativePath = relativePath.substring(0, pos);
        }

        // if the path contains no slash we have nothing to resolve
        if (relativePath.indexOf('/') == -1) {
            return relativePath;
        }

        String[] parts = relativePath.split("/");
        Stack<String> path = new Stack<String>();
        String part;

        for (int i = 0; i < parts.length; i++) {
            part = parts[i].trim();

            if (part.isEmpty() || part.equals(".")) {
            } else if (part.equals("..")) {
                path.pop();
            } else {
                path.add(part);
            }
        }

        // build absolute url
        String absoluteUrl = "";

        if (path.size() > 0) {
            for (int i = 0; i < path.size(); i++) {
                if (i > 0 && path.get(i).indexOf('.') != -1 && path.get(i - 1).equals(path.get(i))) {
                    // if the element before has the same name and it contains
                    // an dot we have probably an file name
                    continue;
                }

                absoluteUrl += "/" + path.get(i);
            }
        } else {
            absoluteUrl = "/";
        }

        // add last slash
        if (relativePath.endsWith("/") && !absoluteUrl.endsWith("/")) {
            absoluteUrl = absoluteUrl + "/";
        }

        return absoluteUrl;
    }
}

Related

  1. resolve(final URL url)
  2. resolve(URL base, String relUrl)
  3. resolve(URL base, String uri)
  4. resolveGoogleRedirect(String url)
  5. resolveManifestResources(final URL manifestUrl, final List resources)
  6. resolvePlatformUrl(String urlspec)
  7. resolveRelativeURL(final URL primaryUrl, final String relativeLoc)
  8. resolveRelativeURL(String contextUri, String relativeUri)