Java – All in One → Java URI – Camposha

Java – All in One

Java – All in One

Java – All in One

Java URI

Java Uri Tutorial and Examples

Let’s start by looking at an example.

import java.lang.IllegalArgumentException;
import java.net.URI;
import java.net.URISyntaxException;

/**
 * Misc. URI/URL utilities
 */
public class URIUtils {

    /**
     * Check that the scheme of a given URI matches the given String.
     * @param uri a String representation of the URI
     * @param scheme the scheme to match against
     * @return Returns false if either argument is null, false if uri
     *         violates RFC 2396 or has an undefined scheme,
     *         otherwise returns whether uri string-matches scheme.
     */
    static public boolean checkScheme(String uri, String scheme) {
        if ( (uri == null) || (scheme == null) )
            return false;
        URI uriObj;
        try {
            uriObj = URI.create(uri);
        }
        catch (IllegalArgumentException e) {
            /* RFC 2396 violation */
            return false;
        }
        String uriScheme = uriObj.getScheme();
        if (uriScheme == null)
            /* scheme undefined */
            return false;
        return (uriScheme.equals(scheme));
    }

    /**
     * Tests whether the given URI matches RFC-2396 specs.
     * @param uri The string to be tested.
     * @param errMsg On false, will be populated with brief failure description.
     * @return Whether the given string is a valid URI.
     */
    static public boolean isValidUri(String uri, StringBuilder errMsg) {
        boolean ret = true;
        if (uri == null) {
            if (errMsg != null) {
                errMsg.append("URI is null");
            }
            ret = false;
        } else {
            try {
                new URI(uri);
            } catch (URISyntaxException se) {
                ret = false;
                if (errMsg != null) {
                    errMsg.append(se.getMessage());
                }
            }
        }

        return ret;
    }

    /**
     * Tests whether the given URI matches RFC-3986 specs.
     * @param uri The string to be tested.
     * @return Whether the given string is a valid URI.
     */
    static public boolean isValidUri(String uri) {
        return isValidUri(uri, null);
    }

}

Leave a Reply

Your email address will not be published. Required fields are marked *

Rating

Not enough ratings to display
Join Us
X