Parsing a URL in Java

前端 未结 4 1939
我寻月下人不归
我寻月下人不归 2021-01-20 16:32

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 b

相关标签:
4条回答
  • 2021-01-20 16:35

    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
    
    0 讨论(0)
  • 2021-01-20 16:36

    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)

    0 讨论(0)
  • 2021-01-20 16:44

    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>

    0 讨论(0)
  • 2021-01-20 16:55

    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.

    0 讨论(0)
提交回复
热议问题