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 开发者_JS百科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...
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.URLEncoderURLEncoder.encode(myurltoencode,"UTF-8");
This will not just fix the [ or ] but also other encoding issues
use this escape code for [ %5B
and for the closing ] use %5D
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.
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);
精彩评论