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?

Archer
  • 5,073
  • 8
  • 50
  • 96
  • Use URLEncoder.encode as you can see in http://stackoverflow.com/questions/4992317/illegal-character-in-path-at-index-16 – Mihai8 Mar 18 '13 at 21:42
  • 1
    yeah, but question is why it works for `java.net.URL` and does not for `java.net.URI`? – Archer Mar 18 '13 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. – user207421 Mar 18 '13 at 23:27
  • you reproduced exactly what I have. I have the exception whith `URI.create` and don't have it with `new URL()` – Archer Mar 19 '13 at 07:48
  • 1
    *Do not* use URLEncoder for this. URLEncoder is for form encoding, not for escaping characters in a URI. – VGR Mar 19 '13 at 11:14
  • Yeah, better to use `URIUtils#encodeUri` from Apache's commons-httpclient – Archer Mar 23 '13 at 17:31

1 Answers1

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.

Joni
  • 108,737
  • 14
  • 143
  • 193