5

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...

Alexander Farber
  • 21,519
  • 75
  • 241
  • 416
sivaraj
  • 1,849
  • 9
  • 35
  • 52
  • Possible duplicate of [How to deal with the URISyntaxException](http://stackoverflow.com/questions/749709/how-to-deal-with-the-urisyntaxexception) – AlikElzin-kilaka Jul 06 '16 at 15:06

4 Answers4

10

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

mrjohn
  • 1,141
  • 2
  • 13
  • 21
4

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

Arthur Rizzo
  • 1,337
  • 15
  • 30
0

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.

AlikElzin-kilaka
  • 34,335
  • 35
  • 194
  • 277
0

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);
Alexander Farber
  • 21,519
  • 75
  • 241
  • 416