我在 Play Framework 2.3.3 中使用包含空格的 url 调用 WS.url() 时遇到问题。所有其他字符都是 url 自动编码的,但不是空格。当我尝试将所有空格更改为“%20”时,由于“%”字符,WS 将其转换为“%2520”。有了空格,我得到了 java.net.URISyntaxException: Illegal character in query。我该如何处理?
部分 URL 的查询字符串:
&input=/mnt/mp3/music/folder/01 - 23.mp3
代码如下所示:
Promise<JsonNode> jsonPromise = WS.url(url).setAuth("", "cube", WSAuthScheme.BASIC).get().map(
new Function<WSResponse, JsonNode>() {
public JsonNode apply(WSResponse response) {
System.out.println(response.getBody());
JsonNode json = response.asJson();
return json;
}
}
);
最佳答案
您应该根据 java.net.URL(Play! 使用它的 WS)的方式“构建”您的 URL。 WS.url() 遵循相同的逻辑。
建议仅对表单数据使用 URLEncoder/Decoder。 来自 JavaDoc:
"Note, the java.net.URI class does perform escaping of its component fields in certain circumstances. The recommended way to manage the encoding and decoding of URLs is to use java.net.URI, and to convert
between these two classes using toURI() and URI.toURL(). The URLEncoder and URLDecoder classes can also be used, but only for HTML form encoding, which is not the same as the encoding scheme defined in RFC2396."
因此,解决方案是使用THIS:
WS.url(baseURL).setQueryString(yourQueryString);
地点:
baseURL
是您的方案 + 主机 + 路径等。yourQueryString
是...嗯,您的查询字符串,但是没有?
: input=/mnt/mp3/music/folder/01 - 23.mp3
或者,如果您想使用更灵活的程序化方法,这个:
WS.url(baseURL).setQueryParameter(param, value);
地点:
param
是查询字符串中的参数名称value
为参数的值
如果您希望在查询中包含多个具有值的参数,您需要通过添加另一个 .setQueryParameter(...)
来链接它们。这意味着这种方法不太适合复杂的多参数查询字符串。
干杯!
关于java - Play Framework WS url 空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25340400/