URL Encoding Strings that aren't valid URIs
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 -
开发者_StackOverflow中文版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!
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()
.
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.
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.
Use java.net.URLEncoder
for example
String s = "somestuff@%#$%^3<<>>";
String encoded_string = URLEncoder.encode(s, "UTF-8");
精彩评论