java - Play Framework WS url 空间

标签 java web-services playframework playframework-2.3

我在 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);

地点:

  1. baseURL 是您的方案 + 主机 + 路径等。
  2. yourQueryString 是...嗯,您的查询字符串,但是没有 ?: input=/mnt/mp3/music/folder/01 - 23.mp3

或者,如果您想使用更灵活的程序化方法,这个:

WS.url(baseURL).setQueryParameter(param, value);

地点:

  1. param 是查询字符串中的参数名称
  2. value为参数的值

如果您希望在查询中包含多个具有值的参数,您需要通过添加另一个 .setQueryParameter(...) 来链接它们。这意味着这种方法不太适合复杂的多参数查询字符串。


干杯!

关于java - Play Framework WS url 空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25340400/

相关文章:

java - Angular 6 + Spring 启动 : Error: "from origin ' http://localhost:420 0' has been blocked by CORS policy"

java - 如何将字符串拆分为整数数组?

java - 递归中的continue关键字

mysql - 通过 IOS 应用程序访问 MySql DB

playframework - 在 IDEA 中编译时出现 sbt.ResolveException

java - 等待后解锁如何发生

java - wsimport Xauthfile 错误

javascript - ScriptManager使用AJAX从WebService异步获取数据并抛出错误?

scala - 使用 Akka Streams 动态压缩 List[Source[ByteString, NotUsed]]

intellij-idea - 如何在 IntelliJ IDEA 中以 Debug模式运行 Play Framework 2.x?