简体   繁体   English

尝试使用URIUtils在Java中使用URI编码字符串

[英]trying to URIEncode a string in java using URIUtils

I'm trying to URIENcode a string in java using URIUtils of spring framework. 我正在尝试使用spring框架的URIUtils对Java中的字符串进行URIENcode。

it supposed to be simple as far as I understood but for some reason the string stays unchanged. 据我了解,它应该很简单,但是由于某种原因,字符串保持不变。

I have the following string: 我有以下字符串:

http://www.foo.bar/foo/bar

and I want to URIEncode it. 我想对其进行URIEncode。

final String ENC = "UTF-8";
String uri = "http://www.foo.bar/foo/bar";
final String result = UriUtils.encodeFragment(uri, ENC);

the result is the same string not encoded. 结果是未编码的相同字符串。

what am I doing wrong? 我究竟做错了什么?

how can I properly URIEncode that string in order to use it in get parameters ? 我如何正确URIEncode该字符串以便在get参数中使用它?

I don't want to use a URLBuilder because i need to use the resulted output and create a hash table for an internal database. 我不想使用URLBuilder,因为我需要使用结果输出并为内部数据库创建哈希表。

thank you 谢谢

I think you can achieve the same using java.net.URLEncoder , avoiding the spring class 我认为您可以使用java.net.URLEncoder达到相同的目的,避免使用spring类

System.out.println(URLEncoder.encode("http://www.foo.bar/foo/bar", "UTF-8"))

would print 会打印

http%3A%2F%2Fwww.foo.bar%2Ffoo%2Fbar

There is an RFC which allows URI building from different parameters: URI templates . 有一个RFC允许从不同的参数构建URIURI模板

Since you use Java, there happens to be an implementation available (disclaimer: yes it's mine). 由于您使用Java,因此碰巧有一个可用的实现 (免责声明:是的,这是我的)。

You could then do like this: 然后,您可以这样做:

// The template
final URITemplate tmpl = new URITemplate("http://my.site/foo{?params*}");

// The query parameters
// Uses Maps from Guava since the lib depends on it
final Map<String, String> params = Maps.newHashMap();
params.put("site", "http://www.foo.bar/foo/bar");

// The template data expansion
final Map<String, VariableValue> data = Maps.newHashMap();
data.put("params", new MapValue(params));

// Expand, build the URL
// The expansion takes care of all the encoding for you
final URL url = new URL(template.expand(data));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM