URL类的getURI()函数将URL对象转换为URI对象。可以将使用RFC 2396编译的任何URL转换为URI。如果非指定格式的URL转换为URI格式,则会产生错误。
函数签名
public URI toURI()
用法
url.toURI()
参数:此方法不接受任何参数。
返回类型:此函数返回一个URI对象,该对象是从该URL对象转换而来的。
异常注意:如果未严格按照RFC2396格式设置此URL,并且无法将其转换为URI,则此函数将引发URISyntaxException。
以下示例将说明toURI()函数的用法:
范例1:
// Java program to convert URL to URI
import java.net.*;
class GFG {
public static void main(String args[])
{
// url and uri objects
URL url = null;
URI uri = null;
try {
// create a URL
url = new URL("https://www.geeksforgeeks.org");
// display the URL
System.out.println("URL: " + url);
// convert the URL to URI
uri = url.toURI();
// display the URI
System.out.println("URI: " + uri);
}
// if any error occurs
catch (Exception e) {
// display the error
System.out.println(e);
}
}
}
输出:
URL: https://www.geeksforgeeks.org
URI: https://www.geeksforgeeks.org
范例2:
// Java program to convert URL to URI
import java.net.*;
class GFG {
public static void main(String args[])
{
// url and uri objects
URL url = null;
URI uri = null;
try {
// create an invalid URL
url = new URL("https://www.geeksfor>geeks.com");
// display the URL
System.out.println("URL: " + url);
// convert the URL to URI
uri = url.toURI();
// display the URI
System.out.println("URI: " + uri);
}
// if any error occurs
catch (Exception e) {
// display the error
System.out.println(e);
}
}
}
输出:
URL: https:// www.geeksfor>geeks.com
java.net.URISyntaxException:
Illegal character in authority at index 8:
https:// www.geeksfor>geeks.com