无效的URL编码字符串 [英] URL Encoding Strings that aren't valid URIs
问题描述
我不确定我是否完全理解URI对象才能正确执行此操作.我希望能够将字符串转换为url编码的字符串.例如,我有一个servlet充当文件处理程序,我需要在标题中指定文件名-
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());
如预期的那样,我得到一个URISyntaxException
,因为我正在编码的字符串不是正确的URI形式.
As expected, I get a URISyntaxException
because the string I'm encoding isn't in proper URI form.
如何编码字符串而不是URL?
How can I encode strings instead of URLs?
使用折旧的URLEncoder无法获得所需的结果,因为它用"+"而不是%20"代替了".
I can't get the results I want using the depreciated URLEncoder because it replaces " " with "+" instead of "%20".
提前谢谢!
推荐答案
您可以使用URLEncoder
并将所有+
替换为%20
.
You could use URLEncoder
and simply replace all +
with %20
.
此外,不推荐使用URLEncoder.encode(String s, String enc)
.
您还可以使用 查看全文