基本 URL 工具
基本的 URL 字符串工具 (getParameter, setParameter, removeParameter 等)。
引言
之前我需要一段通用的代码来获取、设置和移除 URL 字符串中的参数。我找到的很多代码都是用于获取 servlet 请求或 ASP.NET 页面请求的 URL 参数,而不是用于处理 URL 字符串的通用代码。我只找到了用于 GET 参数的通用代码,而且它们通常是通过分割 URL 字符串或使用正则表达式来实现的,因此很难重用它们来实现设置参数或移除参数的功能。
这个 URL 工具类中的方法都是建立在一个通用的方法之上的,该方法对 URL 字符串进行简单的线性搜索,查找所需的参数,并返回参数名称起始位置、值起始位置和值结束位置的偏移量。代码是 Java 编写的,但可以轻松地移植到 C#。
大多数修改输入 URL 的方法都会将修改后的 URL 作为新的 String
对象返回,但可以轻松地转换为在输入 StringBuilder
对象中就地修改 URL。
这个 URL Utility
类的常用方法包括
getParameter()
setParameter()
removeParameter()
addParameter()
getIntParameter()
incrementIntParameter()
源代码中包含单元测试。
Using the Code
一些示例用法
// Sets value to "value1"
String value = UrlUtil.getParameter("protocol://server.suffix?param1=value1",
"param1");
// Sets url to "protocol://server.suffix?param1=value1New"
String url = UrlUtil.setParameter("protocol://server.suffix?param1=value1",
"param1", "value1New);
// Sets url to "protocol://server.suffix"
String url = UrlUtil.removeParameter("protocol://server.suffix?param1=value1",
"param1");
StringBuffer url = new StringBuffer("protocol://server.suffix");
// Sets url to "protocol://server.suffix?param1=value1"
UrlUtil.addParameter(url, "value1");
// Sets value to 1
Integer value = UrlUtil.getIntParameter("protocol://server.suffix?param1=1",
"param1");
// Sets url to "protocol://server.suffix?param1=2"
String url = UrlUtil.incrementIntParameter("protocol://server.suffix?param1=1",
"param1")