3

I am looking for an equivalent to PHP's "parse_url" function in Java. I am not running in Tomcat. I have query strings saved in a database that I'm trying to break apart into individual parameters. I'm working inside of Pentaho, so I only have the Java SE classes to work with. I know I could write a plugin or something, but if I'm going to do all that I'll just write the script in PHP and be done with it.

TLDR: Looking for a Java standard class/function that takes a String and spits out an array of parameters.

Thanks,

Roger

Eng.Fouad
  • 115,165
  • 71
  • 313
  • 417
Roger W.
  • 165
  • 6

4 Answers4

11

You can accomplish that using java.net.URL:

URL url = new URL("http://hostname:port/path?arg=value#anchor");
String protocol = url.getProtocol(); // http
String host = url.getHost(); // hostname
String path = url.getPath(); // /path
int port = url.getPort(); // port
String query = url.getQuery(); // arg=value
String ref = url.getRef(); // anchor
Eng.Fouad
  • 115,165
  • 71
  • 313
  • 417
-1

Here's something quick and dirty (have not compiled it, but you should get the idea.

URL url = new URL("http://...");
String query = url.getQuery();
String paramStrings[] = query.split("\\&");
HashMultiMap<String, String> params = HashMultiMap.create(); // <== google guava class
for (int i=0;iparamStrings.length;i++) {
    String parts[] = params[i].split("=");
    params.put(URLDecoder.decode(parts[0], "UTF-8"), URLDecoder.decode(parts[1], "UTF-8"));
}

Set<String> paramVals = params.get("paramName");

If you don't want to use the guava class, you can accomplish the same thing with some additional code, and a HashMap>

Matt
  • 11,523
  • 2
  • 23
  • 33
-2

No such thing in Java. You will need to parse the strings manually and create your own array. You could create your own parse_url using StringTokenizer, String.split, or Regular Expressions rather easily.

You could also cast those strings from the database back to URL objects and parse them that way, here are the docs.

cam
  • 778
  • 6
  • 9
-4

String has a split function, but you will need to write your own regex to determine how to split the string.

See: http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split(java.lang.String)

Afshin Moazami
  • 2,092
  • 5
  • 33
  • 55
y_s
  • 138
  • 4
  • 1
    I've seen plenty of code examples to break a QS apart by hand. I was figuring since Java was one of the first languages to spring on the internet that it would have some kind of "built in" way for parsing the QS into a HashMap or the like. – Roger W. Nov 16 '12 at 00:20