什么是url只编码Java中的查询键和参数的最佳方法?

时间:2014-03-19 21:28:25

标签: java encoding urlencode url-encoding

我想只编码一个url的查询键和参数(不想编码/,?或&)。在Java中执行此操作的最佳方法是什么?

例如,我想转换

http://www.hello.com/bar/foo?a=,b &c =d

http://www.hello.com/bar/foo?a=%2Cb%20&c%20=d

2 个答案:

答案 0 :(得分:0)

建立这样的网址:

String url = "http://www.hello.com/bar/foo?";
url += "a=" + URLEncoder.encode(value_of_a);
url += "&c=" + URLEncoder.encode(value_of_c);

答案 1 :(得分:0)

我将离开实际的component encoding as a user-supplied function,因为这是一个现有的讨论良好的问题,没有一个简单的JCL解决方案。无论如何,以下是我将如何处理这个问题特殊的问题,不使用第三方库。

虽然正则表达式有时会产生two problems,但我对于提出更严格的方法(例如URI)犹豫不决,因为我不知道它会如何 - 或者即使它会 - 有这么时髦的无效网址。因此,这是使用带有dynamic replacement value的正则表达式的解决方案。

// The following pattern is pretty liberal on what it matches;
// It ought to work as long as there is no unencoded ?, =, or & in the URL
// but, being liberal, it will also match absolute garbage input.
Pattern p = Pattern.compile("\\b(\\w[^=?]*)=([^&]*)");
Matcher m = p.matcher("http://www.hello.com/bar/foo?a=,b &c =d");
StringBuffer sb = new StringBuffer();
while (m.find()) {
    String key = m.group(1);
    String value = m.group(2);
    m.appendReplacement(sb,
        encodeURIComponent(key) + "=" encodeURIComponent(value));
}
m.appendTail(sb);

请参阅ideone example示例,其中包含填充encodeURIComponent

相关问题