In java, what's the best way to read a url and split it into its parts?

前端 未结 4 987
攒了一身酷
攒了一身酷 2021-01-18 01:27

Firstly, I am aware that there are other posts similar, but since mine is using a URL and I am not always sure what my delimiter will be, I feel that I am alright posting my

相关标签:
4条回答
  • 2021-01-18 02:04

    The URL class pretty much does this, look at the tutorial. For example, given this URL:

    http://example.com:80/docs/books/tutorial/index.html?name=networking#DOWNLOADING
    

    This is the kind of information you can expect to obtain:

    protocol = http
    authority = example.com:80
    host = example.com
    port = 80
    path = /docs/books/tutorial/index.html
    query = name=networking
    filename = /docs/books/tutorial/index.html?name=networking
    ref = DOWNLOADING
    
    0 讨论(0)
  • 2021-01-18 02:13

    you can use String class split() and store the result into the String array then iterate the array and store the variable and value into the Map.

    public class URLSPlit {
        public static Map<String,String> splitString(String s) {
            String[] split = s.split("[= & ?]+");
            int length = split.length;
            Map<String, String> maps = new HashMap<>();
    
            for (int i=0; i<length; i+=2){
                  maps.put(split[i], split[i+1]);
            }
    
            return maps;
        }
    
        public static void main(String[] args) {
            String word = "q=java+online+compiler&rlz=1C1GCEA_enIN816IN816&oq=java+online+compiler&aqs=chrome..69i57j69i60.18920j0j1&sourceid=chrome&ie=UTF-8?k1=v1";
            Map<String, String> newmap =  splitString(word);
    
            for(Map.Entry map: newmap.entrySet()){
                System.out.println(map.getKey()+"  =  "+map.getValue());
            }
        }
    }
    
    0 讨论(0)
  • 2021-01-18 02:15

    Instead of url.split(".org"); try url.split("/"); and iterate through your array of strings.

    Or you can look into regular expressions. This is a good example to start with.

    Good luck on your homework.

    0 讨论(0)
  • 2021-01-18 02:22

    This is how you should split your URL parts: http://docs.oracle.com/javase/tutorial/networking/urls/urlInfo.html

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