Click here to Skip to main content
Click here to Skip to main content

Tagged as

Basic URL Utilities

, 24 Nov 2008 CPOL
Rate this:
Please Sign up or sign in to vote.
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:

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

Share

About the Author

JamesVV
Software Developer
Unknown
No Biography provided

Comments and Discussions

 
-- There are no messages in this forum --
| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.141223.1 | Last Updated 24 Nov 2008
Article Copyright 2008 by JamesVV
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid