Click here to Skip to main content
15,891,657 members
Articles / Programming Languages / Java
Article

Basic URL Utilities

Rate me:
Please Sign up or sign in to vote.
4.20/5 (6 votes)
24 Nov 2008CPOL1 min read 23.9K   399   12  
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)


Written By
Software Developer
Unknown
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --