2

How do I check whether any URL contains one or more parameters or not?

For example, if the URL is

.../PaymentGatewayManager?mode=5015

then we should be able to know that URL contains one parameter. Or if the URL is

.../PaymentGatewayManager

then we should be able to know that the URL does not contain any parameter. Or if the URL is

.../PaymentGatewayManager?mode=5015&test=456123&abc=78

then we should be able to know that the URL contains three parameters, and we should also be able to know the parameter name and values of that using any regular expression in Java.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Bhavik Ambani
  • 6,557
  • 14
  • 55
  • 86
  • 2
    Can you please check this [url][1] [1]: http://stackoverflow.com/questions/27745/getting-parts-of-a-url-regex Hope that is your answer – Sandeep Nair Feb 03 '12 at 11:13

3 Answers3

4

If you wanted to do it with a regular expression (this can be optimized as well to do a search inside a group):

public static void main(String[] args) {
    String input = ".../PaymentGatewayManager?mode=5015&test=456123&test2=SomeRandomValue&abc=78";
    if(input.contains("?")){
        System.out.println("It does contain parameters");
        input = "&" + input.substring(input.indexOf("?")+1) + "&";

        System.out.println(input);

        Pattern p = Pattern.compile("&?(\\w.+?)=(.+?)&");
        Matcher m = p.matcher(input);

        while(m.find()){
            System.out.println("Token ->" + m.group(1));
            System.out.println("Value ->" + m.group(2));
        }
    }
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Eugene
  • 117,005
  • 15
  • 201
  • 306
3

Use the methods of java.net.URI to get everything about an URL.

Edit: Use URI, not URL (thanks McDowell).

2

You can String.split() the URL, or tokenize it using java.util.StringTokenizer, using ? as the splitter character. If you get more than one pieces, then it's sure that the URL contains parameters.

To get the parameters, split the second part by & in the same way. You'll get the parameters. Splitting each one of them by = will give you the names and values.

Sufian Latif
  • 13,086
  • 3
  • 33
  • 70