我尝试通过以下方式从 Java 代码调用 URL:
userId = "Ankur";
template = "HelloAnkur";
value= "ParamValue";
String urlString = "https://graph.facebook.com/" + userId + "/notifications?template=" +
template + "&href=processThis.jsp?param=" + value + "&access_token=abc123";
我在这方面遇到以下问题:
- 当我执行
println(urlString)
时,我发现urlString
仅具有第一个与号 (&
) 之前的值。也就是说,它看起来像:https://graph.facebook.com/Ankur/notifications?template=HelloAnkur
以及其余部分(应该是&href=processThis.jsp? param=ParamValue&access_toke=abc123
) 被切断。这是为什么?如何获取并保留urlString
中的完整值? Java 字符串中的&
是否需要转义?如果需要,该怎么做? - 请注意,我尝试在此查询中传递一个(相对)URL 作为参数值(
href
的值为processThis.jsp?param=ParamValue
。如何传递这种类型的href
值而不将其与此 URL (urlString
) 的查询混合,该 URL 只有三个参数template
>、href
和access_token
?即如何 Conceal 或转义?
和=
?进一步,什么如果value
是Param Value
(带空格),我需要做什么? - 请注意,
template
的值为HelloAnkur
(不含空格)。但如果我希望它有空间,就像Hello Ankur
中那样,我该怎么做呢?我应该把它写成Hello%20Ankur
还是Hello Ankur
就可以了? - 我需要这样的解决方案:可以创建
URL url = new URL(urlString)
,或者可以通过URI 创建
.请描述到目前为止您的答案,因为在 Java 中创建安全 URL 并不简单。url
谢谢!
最佳答案
(这将成为经典)
使用 URI 模板 (RFC 6570)。使用this implementation (免责声明:我的),您可以完全避免所有编码问题:
// Immutable, can be reused as many times as you wish
final URITemplate template = new URITemplate("https://graph.facebook.com/{userId}"
+ "/notifications?template={template}"
+ "&href=processThis.jsp?param={value}"
+ "&access_token=abc123");
final Map<String, VariableValue> vars = new HashMap<String, VariableValue>();
vars.put("userId", new ScalarValue("Ankur"));
vars.put("template", new ScalarValue("HelloAnkur"));
vars.put("value", new ScalarValue("ParamValue");
// Build the expanded string
final String expanded = template.expand(vars);
// Go with the string
请注意,URI 模板不仅允许标量值,还允许数组(RFC 称之为“列表”——在上面实现为 ListValue
)和映射(RFC 称之为“关联数组”) "-- 在上面实现为 MapValue
)。
关于java - 如何处理 Java 字符串中的 & 符号并将 URL 作为查询参数值发送?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16967161/