2025年4月5日 星期六 乙巳(蛇)年 正月初六 设为首页 加入收藏
rss
您当前的位置:首页 > 计算机 > 编程开发 > Java

Java:解析URL的参数:协议/主机/端口号/文件路径/请求参数/定位位置

时间:05-15来源:作者:点击数:26

URL(Uniform Resource Locator)中文名为统一资源定位符

URL的组成部分

  • protocol://host:port/path?query#fragment

解析示例

  • https://www.demo.com/getList?page=1&size=30#top

解析结果

部分 英文名 示例
协议 protocol https
主机 host www.demo.com
端口号 port 443(HTTPS 协议默认的端口号为 443)
文件路径 path /getList
请求参数 query page=1&size=30
定位位置 fragment top

代码示例

  • package com.example.demo;
  • import org.junit.Test;
  • import java.net.MalformedURLException;
  • import java.net.URL;
  • public class URLTests {
  • @Test
  • public void testURL() throws MalformedURLException {
  • String urlString = "https://www.demo.com/getList?page=1&size=30#top";
  • URL url = new URL(urlString);
  • // 协议
  • String protocol = url.getProtocol();
  • // 主机名
  • String host = url.getHost();
  • // 端口
  • Integer port = url.getPort();
  • // 默认端口
  • Integer defaultPort = url.getDefaultPort();
  • // 路径
  • String path = url.getPath();
  • // 请求参数
  • String query = url.getQuery();
  • // 定位位置
  • String ref = url.getRef();
  • System.out.println("protocol: " + protocol);
  • // https
  • System.out.println("host: " + host);
  • // www.demo.com
  • System.out.println("port: " + port);
  • // -1
  • System.out.println("defaultPort: " + defaultPort);
  • // 443
  • System.out.println("path: " + path);
  • // /getList
  • System.out.println("query: " + query);
  • // page=1&size=30
  • System.out.println("ref: " + ref);
  • // top
  • }
  • }
方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门