[英]Encode content part of URL in Java
I have a URL string with replaceable values: 我有一个具有可替换值的URL字符串:
http://DOMAIN:PORT/sendmsg?user=test&passwd=test00&text={CONTENT}
I have to encode the content part, so I tried this: 我必须对内容部分进行编码,因此我尝试了以下操作:
String tempContent = URLEncoder.encode(content, "UTF-8");
tempContent had this value: This+is+test+one I do not want the + where spaces is. tempContent具有以下值:this + is + test + one我不希望空格所在的+。 Spaces MUST be represented by %20
空格必须用%20表示
Now, I can do this: 现在,我可以这样做:
String tempContent = content.replaceAll(" ", "%20");
BUT that only covers the spaces and I don't have control over the content input. 但是仅覆盖空格,我无法控制内容输入。 Is there any other efficient way to encode URL content in Java?
还有其他有效的方法可以用Java编码URL内容吗? URLEncoder does not do what I want.
URLEncoder不能满足我的要求。
Thanks in advance.. 提前致谢..
I finally got this to work, I used 我终于有了这个工作,我曾经
URIUtil.encodeQuery(url);
Correctly encoded spaces with %20. 正确编码了%20的空格。 This comes from the Apache commons-httpclient project.
这来自Apache commons-httpclient项目。
One solution is to use a library which expands URI templates (this is RFC 6570). 一种解决方案是使用扩展URI模板的库(这是RFC 6570)。 I know of at least one (disclaimer: this is mine).
我知道至少一个 (免责声明:这是我的)。
Using this library, you can do this: 使用此库,您可以执行以下操作:
final URITemplate template
= new URITemplate("http://DOMAIN:PORT/sendmsg?user=test&passwd=test00&text={CONTENT}");
final VariableValue value = new ScalarValue(content);
final Map<String, VariableValue> vars = new HashMap<String, VariableValue>();
vars.put("CONTENT", value);
// Obtain expanded template
final String s = template.expand(vars);
// Now build a URL out of it
Maps are allowed as values (this is a MapValue
in my implementation; the RFC calls these "associative arrays"), so for instance, if you had a map with (correctly filled) entries for user
, passwd
and text
, you could write your template as: 允许使用地图作为值(在我的实现中,这是
MapValue
; RFC称为这些“关联数组”),因此,例如,如果您的地图包含(正确填充的) user
, passwd
和text
条目,则可以编写模板为:
http://DOMAIN:PORT/sendmsg{?parameters*}
With a map value parameters
containing: 具有地图值的
parameters
包含:
"user": "john",
"passwd": "doe",
"content": "Hello World!"
this would expand as: 它将扩展为:
http://DOMAIN:PORT/sendmsg?user=john&passwd=doe&content=Hello%20World%21
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.