2

I'm confused with why this is valid and not throwing an exception:

final URL u = new URL("https:// google . c o m foo bar")

Isn't this an invalid URL?

4
  • I'd check the docs. It's possible it URL encodes anything you put in the constructor, which would replace the space with %20. Commented Jan 15, 2020 at 23:29
  • u.toURI() throws an exception, but the constructor does not. Commented Jan 15, 2020 at 23:30
  • @Kousha It does, but only "if no protocol is specified, or an unknown protocol is found, or spec is null". "https://" is a valid protocol specification, and " google . c o m foo bar" isn't null, so... It seems a weird decision to only enforce strict parsing according to RFC2396 in toURI(), though. Commented Jan 15, 2020 at 23:31
  • URL constructor does not do strict validation of the URL path. If want URL encoded use URLEncoder.encode() which would return "https%3A%2F%2F+google+.+c+o+m+foo+bar" for the input above. Commented Jan 15, 2020 at 23:42

1 Answer 1

1

Yes. java.net.URL is a very old class which was part of Java 1.0. It does little to no checking of the syntax of its String argument.

Later, the java.net.URI class was added, which does all of the proper checks. And a valid URI can be converted to a URL with the toURL() method.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.