2
java.net.URI.create("http://adserver.adtech.de/adlink|3.0")

throws

java.net.URISyntaxException: 
Illegal character in path at index 32: http://adserver.adtech.de/adlink|3.0

although

new java.net.URL("http://adserver.adtech.de/adlink|3.0")

works just fine.

UPDATE 1

although

new org.apache.commons.httpclient.URI("http://adserver.adtech.de/adlink|3.0")

also works perfectly.

What's the reason?

6
  • Use URLEncoder.encode as you can see in stackoverflow.com/questions/4992317/… Commented Mar 18, 2013 at 21:42
  • 1
    yeah, but question is why it works for java.net.URL and does not for java.net.URI? Commented Mar 18, 2013 at 21:46
  • Cannot reproduce. Both URI.create() and new URI() throw that exception. In the case of URI.create() it is wrapped in an IllegalArgumentException as per the Javadoc. Java version 1.7.0_17. Commented Mar 18, 2013 at 23:27
  • you reproduced exactly what I have. I have the exception whith URI.create and don't have it with new URL() Commented Mar 19, 2013 at 7:48
  • 1
    Do not use URLEncoder for this. URLEncoder is for form encoding, not for escaping characters in a URI. Commented Mar 19, 2013 at 11:14

1 Answer 1

6

The constructor of URI that takes a single String argument requires that you follow the strict syntax rules that RFC 2396 defines for URIs. According to those rules | should be encoded as %7C. The other constructors can encode the URI components for you, so for example this won't throw an exception:

new java.net.URI("http", "//adserver.adtech.de/adlink|3.0", null);

The URL class on the other does not enforce the URI syntax rules. In fact, it is your responsibility to encode the components that should be encoded; the URL class won't help you. From the documentation:

It is the responsibility of the caller to encode any fields, which need to be escaped prior to calling URL, and also to decode any escaped fields, that are returned from URL.

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

2 Comments

The java.net.URI constructors in question have existed since java 1.4
iv missread it, i thought it is a 2 arg constructor.

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.