sivaraj
sivaraj

Reputation: 1867

How to solve the exception Illegal character in path?

I am displaying images from an URL using XML parsing and some images are displaying very well, but sometimes I get exception like

Illegal character in path at index 113: http://www.theblacksheeponline.com/party_img/thumbspps/12390867930_15951_186997180114_709920114_4296270_6115611_n[1].jpg

How to solve this problem, please provide some sample code...

Upvotes: 6

Views: 31976

Answers (4)

Alexander Farber
Alexander Farber

Reputation: 22968

The modern way to handle this problem in a Java program or servlet would be to use OWASP.

For example, if using Maven to build your program, add the following to your pom.xml file

<properties>
    <owasp.version>1.2.1</owasp.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.owasp.encoder</groupId>
        <artifactId>encoder</artifactId>
        <version>${owasp.version}</version>
    </dependency>     
 </dependencies>

And then call the Encode.forHtml method:

String safeStr= Encode.forHtml(str);

Upvotes: 0

AlikElzin-kilaka
AlikElzin-kilaka

Reputation: 35991

This did the trick:

URL url = new URL("http://www.theblacksheeponline.com/party_img/thumbspps/12390867930_15951_186997180114_709920114_4296270_6115611_n[1].jpg");
URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(), url.getQuery(), url.getRef());

URLEncoder is used for web forms application/x-www-form-urlencoded mime-type - not http network addresses.

Upvotes: 0

mrjohn
mrjohn

Reputation: 1161

Special characters need escaping such as %5B for [ and %5D for ]

You can use the java.net.URLEncoder to encode the URL as in

java.net.URLEncoder

URLEncoder.encode(myurltoencode,"UTF-8");

This will not just fix the [ or ] but also other encoding issues

Upvotes: 11

Arthur Rizzo
Arthur Rizzo

Reputation: 1347

use this escape code for [ %5B and for the closing ] use %5D

Upvotes: 4

Related Questions