📅  最后修改于: 2020-09-28 03:10:11             🧑  作者: Mango
Java URL类代表一个URL。 URL是“统一资源定位器”的缩写。它指向万维网上的资源。例如:
https://www.javatpoint.com/java-tutorial
URL包含许多信息:
URL(字符串规范)
从字符串表示形式创建URL的实例。
URL(字符串协议,字符串主机,int端口,字符串文件)
根据给定的协议,主机,端口号和文件创建URL的实例。
URL(字符串协议,字符串主机,int端口,字符串文件,URLStreamHandler处理程序)
根据给定的协议,主机,端口号,文件和处理程序创建URL的实例。
URL(字符串协议,字符串主机,字符串文件)
根据给定的协议名称,主机名和文件名创建URL的实例。
URL(URL上下文,字符串规范)
通过在指定的上下文中解析给定的规范来创建URL的实例。
URL(URL上下文,字符串规范,URLStreamHandler处理程序)
通过在给定上下文中使用指定的处理程序解析给定的规范来创建URL的实例。
java.net.URL类提供了许多方法。 URL类的重要方法如下。
Method | Description |
---|---|
public String getProtocol() | it returns the protocol of the URL. |
public String getHost() | it returns the host name of the URL. |
public String getPort() | it returns the Port Number of the URL. |
public String getFile() | it returns the file name of the URL. |
public String getAuthority() | it returns the authority of the URL. |
public String toString() | it returns the string representation of the URL. |
public String getQuery() | it returns the query string of the URL. |
public String getDefaultPort() | it returns the default port of the URL. |
public URLConnection openConnection() | it returns the instance of URLConnection i.e. associated with this URL. |
public boolean equals(Object obj) | it compares the URL with the given object. |
public Object getContent() | it returns the content of the URL. |
public String getRef() | it returns the anchor or reference of the URL. |
public URI toURI() | it returns a URI of the URL. |
//URLDemo.java
import java.net.*;
public class URLDemo{
public static void main(String[] args){
try{
URL url=new URL("http://www.javatpoint.com/java-tutorial");
System.out.println("Protocol: "+url.getProtocol());
System.out.println("Host Name: "+url.getHost());
System.out.println("Port Number: "+url.getPort());
System.out.println("File Name: "+url.getFile());
}catch(Exception e){System.out.println(e);}
}
}
输出:
Protocol: http
Host Name: www.javatpoint.com
Port Number: -1
File Name: /java-tutorial
让我们看看Java中的另一个示例URL类。
//URLDemo.java
import java.net.*;
public class URLDemo{
public static void main(String[] args){
try{
URL url=new URL("https://www.google.com/search?q=javatpoint&oq=javatpoint&sourceid=chrome&ie=UTF-8");
System.out.println("Protocol: "+url.getProtocol());
System.out.println("Host Name: "+url.getHost());
System.out.println("Port Number: "+url.getPort());
System.out.println("Default Port Number: "+url.getDefaultPort());
System.out.println("Query String: "+url.getQuery());
System.out.println("Path: "+url.getPath());
System.out.println("File: "+url.getFile());
}catch(Exception e){System.out.println(e);}
}
}
输出:
Protocol: https
Host Name: www.google.com
Port Number: -1
Default Port Number: 443
Query String: q=javatpoint&oq=javatpoint&sourceid=chrome&ie=UTF-8
Path: /search
File: /search?q=javatpoint&oq=javatpoint&sourceid=chrome&ie=UTF-8