How to parse or split URL Address in Java?

后端 未结 2 491
南笙
南笙 2020-11-30 07:48

If I have url address.

https://graph.facebook.com/me/home?limit=25&since=1374196005

Can I get(or split) parameters (avoiding hard coding)?

Like t

2条回答
  •  伪装坚强ぢ
    2020-11-30 08:31

    For pure Java , I think this code should work:

    import java.net.URL;
    import java.net.URLDecoder;
    import java.util.HashMap;
    import java.util.Map;
    
    public class UrlTest {
        public static void main(String[] args) {
            try {
                String s = "https://graph.facebook.com/me/home?limit=25&since=1374196005";
                URL url = new URL(s);
                String query = url.getQuery();
                Map data = new HashMap();
                for (String q : query.split("&")) {
                    String[] qa = q.split("=");
                    String name = URLDecoder.decode(qa[0]);
                    String value = "";
                    if (qa.length == 2) {
                        value = URLDecoder.decode(qa[1]);
                    }
    
                    data.put(name, value);
                }
                System.out.println(data);
            } catch (Exception e) {
                e.printStackTrace();
            }
    
        }
    
    }
    

提交回复
热议问题