-1
String url="http://someexample.com/?cid=cid123 &club_id=club123&s4c=10&dom=someexample.com&hash=testhash";
String[] params = url.split("&");  
for (String param : params)  {  
    String name = param.split("=")[0];  
    String value = param.split("=")[1];  
    System.out.println(name+":"+value);
}  

It displays Output

http://someexample.com/?cid:cid123
club_id:club123
s4c:10
dom:someexample.com
hash:testhash

But I want to get cid as well so I tried the following

    String delimeter1="?";
    String delimeter2="&";
    url=url.replace(delimeter1, delimeter2);

And when I ran the program it gave me following error

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1

Please suggest me what I am doing wrong here ?

afzalex
  • 8,598
  • 2
  • 34
  • 61
Madan Madan
  • 674
  • 1
  • 11
  • 28

3 Answers3

0

By replacing ? with &, the first part of the URL (http://someexample.com/) becomes a param too. Splitting this one with the = will only return 1 part, as it does not contain any equal sign. And then, accessing [1] of it will fail.

I would suggest to only split a param if it contains an equal sign:

if (param.contains("=") { ... }
cello
  • 5,356
  • 3
  • 23
  • 28
0

I suggest you to change the url String and get only the part of the String after ?.

String url="http://someexample.com/?cid=cid123 &club_id=club123&s4c=10&dom=someexample.com&hash=testhash";
url = url.substring(url.indexOf('?')+1);
String[] params = url.split("&");  
for (String param : params)  {  
    String name = param.split("=")[0];  
    String value = param.split("=")[1];  
    System.out.println(name+":"+value);
} 
afzalex
  • 8,598
  • 2
  • 34
  • 61
0

Use URL class to help with parsing. Also, code defensively for when there is not "cid" in the query:

URL url = new URL("http://someexample.com/?"
    + "cid=cid123&club_id=club123&s4c=10&"
    + "dom=someexample.com&hash=testhash");
System.out.println(url.getQuery());
String[] params = url.getQuery().split("&");

for (String param : params) {
  String[] pair = param.split("=");
  if (pair.length == 2 && pair[0].equals("cid")) {
    String value = pair[1];
    System.out.printf("cid is %s", value);
  }
}
LeffeBrune
  • 3,441
  • 1
  • 23
  • 36