Introduction
A while back, I needed a general-purpose code to get, set, and remove parameters from a URL string. Much of the code I found online were for getting URL parameters for servlet requests or ASP.NET page requests, not general-purpose code for working with a URL string. I only found general-purpose code for GET-parameters, and it invariably worked by splitting the URL string or by using Regular Expressions, and so could not easily be re-used to implement set-parameter or remove-parameter.
The methods in this URL utility class are all built on top of a common method that does a simple linear-search of a URL string for the desired parameter and returns the offsets of the parameter name start, value start, and value end. The code is Java, but can be trivially ported to C#.
Most of the methods which modify their input URLs return the modified URL as a new String
object, but could be easily converted to modify a URL in an input StringBuilder
object in-place.
The methods of this URL Utility
class are:
getParameter()
setParameter()
removeParameter()
addParameter()
getIntParameter()
incrementIntParameter()
Unit tests are included with the source.
Using the Code
Some example uses:
String value = UrlUtil.getParameter("protocol://server.suffix?param1=value1",
"param1");
String url = UrlUtil.setParameter("protocol://server.suffix?param1=value1",
"param1", "value1New);
// Sets url to "protocol:
String url = UrlUtil.removeParameter("protocol://server.suffix?param1=value1",
"param1");
StringBuffer url = new StringBuffer("protocol://server.suffix");
UrlUtil.addParameter(url, "value1");
Integer value = UrlUtil.getIntParameter("protocol://server.suffix?param1=1",
"param1");
String url = UrlUtil.incrementIntParameter("protocol://server.suffix?param1=1",
"param1")