John Strickler
John Strickler

Reputation: 25421

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!

Upvotes: 0

Views: 3481

Answers (4)

user207421
user207421

Reputation: 311054

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().

Upvotes: 2

rid
rid

Reputation: 63600

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.

Upvotes: 1

chrixian
chrixian

Reputation: 2811

Use java.net.URLEncoder

for example

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

Upvotes: -2

x4u
x4u

Reputation: 14085

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.

Upvotes: 1

Related Questions