Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / Java

Basic URL Utilities

4.20/5 (6 votes)
24 Nov 2008CPOL1 min read 24K   401  
Basic URL string utilites (getParameter, setParameter, removeParameter, and others).

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:

Java
// 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")

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)