Java URI from toURI(String s)

Here you can find the source of toURI(String s)

Description

to URI

License

Open Source License

Declaration

public static URI toURI(String s) throws URISyntaxException 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2010 The Eclipse Foundation and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:/* www  .  j  a v a 2s  . c om*/
 *     The Eclipse Foundation - initial API and implementation
 *******************************************************************************/

import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLDecoder;

public class Main {
    public static URI toURI(String s) throws URISyntaxException {
        try {
            return new URI(s);
        } catch (URISyntaxException e) {
            URL url;
            try {
                url = new URL(s);
            } catch (MalformedURLException e1) {
                //throw original error
                throw e;
            }
            if (!s.equals(url.toString())) {
                try {
                    return url.toURI();
                } catch (URISyntaxException e1) {
                    //keep going
                }
            }
            try {
                return new URI(url.getProtocol(), url.getAuthority(), decode(url.getPath()),
                        encodeQuery(url.getQuery()), url.getRef());
            } catch (URISyntaxException e1) {
                //throw original error
                throw e;
            }
        }
    }

    private static String decode(String path) {
        try {
            return path == null ? null : URLDecoder.decode(path, "UTF-8"); //$NON-NLS-1$
        } catch (UnsupportedEncodingException e) {
            //should not be possible
            return path;
        }
    }

    private static String encodeQuery(String query) {
        return query == null ? null : query.replace(" ", "+"); //$NON-NLS-1$//$NON-NLS-2$
    }
}

Related

  1. toURI(String location)
  2. toURI(String location)
  3. toURI(String location)
  4. toUri(String path)
  5. toURI(String path)
  6. toURI(String str)
  7. toURI(String str)
  8. toURI(String sUri)
  9. toURI(String uri)