java url 使用_Java URL toURI()用法及代码示例

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值