In java, what's the best way to read the url and split it apart?

Firstly, I know that there are other similar messages, but since mine uses the URL, and I'm not always sure what my separator will be, I feel like I'm fine posting my question. My job is to make a rude web browser. I have a textField in which the user enters the desired URL. Then I obviously have to go to this web page. Here is an example from my teacher about how my code would look something like this. This is the code I have to send to my socket. Example URL: http://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol

GET /wiki/Hypertext_Transfer_Protocol HTTP/1.1\n Host: en.wikipedia.org\n \n 

So my question is this: I'm going to read only one full line in the URL, so how do I extract only the part of "en.wikipedia.org" and only the extension? I tried this as a test:

  String url = "http://en.wikipedia.org/wiki/Hypertext Transfer Protocol"; String done = " "; String[] hope = url.split(".org"); for ( int i = 0; i < hope.length; i++) { done = done + hope[i]; } System.out.println(done); 

It just prints the URL without the ".org" in it. I think I'm on the right track. I'm just not sure. In addition, I know that websites can have different endings (.org, .com, .edu, etc.), so I assume that I will need several if statements that compensate for different possible endings. Basically, how do I get the URL in two parts that I need?

+5
source share
4 answers

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

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

This is the information you can get:

 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 
+30
source
+1
source

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

Or you can search for regular expressions. This is a good example to start with.

Good luck with your homework.

+1
source

You can use the String split() class and save the result in a String array, then iterate through the array and save the variable and value in 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
source

All Articles