Java URI getPort()方法及示例

来源:这里教程网 时间:2026-02-17 21:16:04 作者:

Java URI getPort()方法及示例

getPort() 函数是URL类的一部分。getPort()函数返回一个指定的URL的端口。如果没有设置端口,该函数将返回端口号或-1。

函数签名

public int getPort()

语法

url.getPort()

返回类型 :该函数返回 整数 类型

参数 :该函数不需要任何参数。

下面的程序说明了getPort()函数的使用。

例1
指定URL的显示端口

// Java program to show the use of the function getPort()import java.net.*;class Solution {    public static void main(String args[])    {        // url  object        URL url = null;          try {            // create a URL            url = new URL("https:// www.geeksforgeeks.org:80");              // get the  port            int _port = url.getPort();              // display the URL            System.out.println("URL = " + url);              // display the  port            System.out.println(" Port=" + _port);        }          // if any error occurs        catch (Exception e) {              // display the error            System.out.println(e);        }    }}

输出:

URL = https:// www.geeksforgeeks.org:80 Port=80

例2: 创建一个没有定义端口的URL,然后尝试用getPort()函数来获取端口。

// Java program to show the// use of the function getPort()  import java.net.*;  class Solution {    public static void main(String args[])    {        // url object        URL url = null;          try {            // create a URL            url = new URL("https:// www.geeksforgeeks.org");              // get the port            int _port = url.getPort();              // display the URL            System.out.println("URL = " + url);              // display the port            System.out.println(" Port=" + _port);        }          // if any error occurs        catch (Exception e) {              // display the error            System.out.println(e);        }    }}

输出:

URL = https:// www.geeksforgeeks.org Port=-1

相关推荐