Android 如何解决路径中的异常非法字符?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3753852/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 11:40:02  来源:igfitidea点击:

How to solve the exception Illegal character in path?

android

提问by sivaraj

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

我正在使用 XML 解析显示来自 URL 的图像,并且一些图像显示得很好,但有时我会遇到类似的异常

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

索引 113 路径中的非法字符:http: //www.theblacksheeponline.com/party_img/thumbspps/12390867930_15951_186997180114_709920114_4296270_61151611_n[

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

如何解决这个问题,请提供一些示例代码...

回答by mrjohn

Special characters need escaping such as %5Bfor [ and %5Dfor ]

特殊字符需要转义,例如%5Bfor [ 和%5Dfor ]

You can use the java.net.URLEncoderto encode the URL as in

您可以使用java.net.URLEncoder对 URL 进行编码,如

java.net.URLEncoder

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

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

这不仅可以解决 [ 或 ] 问题,还可以解决其他编码问题

回答by Arthur Rizzo

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

将此转义码用于 [ %5B和结束 ] 使用%5D

回答by AlikElzin-kilaka

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-urlencodedmime-type - not http network addresses.

URLEncoder 用于 web 表单application/x-www-form-urlencodedmime-type - 而不是 http 网络地址。

回答by Alexander Farber

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

在 Java 程序或 servlet 中处理这个问题的现代方法是使用OWASP

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

例如,如果使用 Maven 构建您的程序,请将以下内容添加到您的 pom.xml 文件中

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

然后调用Encode.forHtml方法:

String safeStr= Encode.forHtml(str);