URL Encoding Strings that aren't valid URIs

断了今生、忘了曾经 提交于 2019-12-12 02:25:38

问题


I'm not sure I understand the URI object completely to do this properly. I want to be able to convert a string into a url-encoded string. For example, I have a servlet acting as a file handler and I need to specify the file name in the header -

response.setHeader("Content-disposition", "attachment;filename=" + new URI(filename).toUrl());

As expected, I get a URISyntaxException because the string I'm encoding isn't in proper URI form.

How can I encode strings instead of URLs?

I can't get the results I want using the depreciated URLEncoder because it replaces " " with "+" instead of "%20".

Thanks in advance!


回答1:


You could use URLEncoder and simply replace all + with %20.

Also, URLEncoder.encode(String s, String enc) is not deprecated.

You could also use org.springframework.web.util.UriUtils.encodeUri.




回答2:


URLEncoder isn't for URLs, curiously enough, it is really for URL arguments and other things that need application/x-www-form-urlencoded MIME-encoding. The easiest way I have found to URL-encode an arbitrary string 's' is new URI(null, s, null).toASCIIString().




回答3:


You should better use new File( filename ).toURI().toURL(). This will create the correct encoding for a file name. It also works for relative file names and files that don't exist. Actually this construct doesn't perform any file system access.




回答4:


Use java.net.URLEncoder

for example

String s = "somestuff@%#$%^3<<>>";
String encoded_string = URLEncoder.encode(s, "UTF-8");


来源:https://stackoverflow.com/questions/6230693/url-encoding-strings-that-arent-valid-uris

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!