Search code examples
javaurl-encoding

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 -

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!


Solution

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