URI/URL and String what is the difference?

2020-06-16 05:36发布

问题:

This is out of curiosity, no code required, I tried using the worlds best search engine to get my answers but figured out nothing worthwhile.

Whats the difference between a URI/URL and a string representing that URI/URL?

Why do we have to parse it?

What does parsing a string into URI/URL do to the string such that it is treated differently?

Why does HTTP get support typing URL as a string?

回答1:

URI/URL is constrained. To be valid it has to follow a certain format.

By saying that they only accept a URI/URL methods are saying that the string they accept has to be in that format. This also makes it clearer "at a glance" what the method is expecting (a URL) rather than potentially any String.

If the String isn't in that format then it is detected immediately when you try and create the URL object rather than at some unknown point in the future when you try and use that URL in a method.

So by doing this it increases type safety, makes code more readable, and causes failures to happen closer to the root cause of the failure rather than at some unknown point in the future.

You also get methods to construct the URL properly from its parts, to open resources using the URL, etc. So it's a lot more than just a String. Take a look at the Javadoc to see how many methods it provides:

http://docs.oracle.com/javase/7/docs/api/java/net/URL.html



标签: java url