java url scheme解析url
时间: 2023-08-28 17:08:07 浏览: 122
Java中可以使用Java.net.URL类解析URL。以下是解析URL的步骤:
1. 创建URL对象
```java
URL url = new URL("http://www.example.com/test.html?param1=value1¶m2=value2#section1");
```
2. 获取URL的协议
```java
String protocol = url.getProtocol(); // 返回值为"http"
```
3. 获取URL的主机名
```java
String host = url.getHost(); // 返回值为"www.example.com"
```
4. 获取URL的端口号
```java
int port = url.getPort(); // 返回值为-1,因为该URL使用默认端口号
```
5. 获取URL的路径
```java
String path = url.getPath(); // 返回值为"/test.html"
```
6. 获取URL的查询参数
```java
String query = url.getQuery(); // 返回值为"param1=value1¶m2=value2"
```
7. 获取URL的锚点
```java
String anchor = url.getRef(); // 返回值为"section1"
```
完整示例代码如下:
```java
import java.net.URL;
public class URLParser {
public static void main(String[] args) throws Exception {
URL url = new URL("http://www.example.com/test.html?param1=value1¶m2=value2#section1");
String protocol = url.getProtocol();
String host = url.getHost();
int port = url.getPort();
String path = url.getPath();
String query = url.getQuery();
String anchor = url.getRef();
System.out.println("Protocol: " + protocol);
System.out.println("Host: " + host);
System.out.println("Port: " + port);
System.out.println("Path: " + path);
System.out.println("Query: " + query);
System.out.println("Anchor: " + anchor);
}
}
```
阅读全文