play框架 - 如何在play框架中使用java代码发送post请求

时间:2014-09-14 19:12:21

标签: java playframework

目前我正在转向开发框架来开发,但我对这个精彩框架不熟悉。 我只想向远程服务器发送一个帖子请求并获得响应。

如果我使用泽西岛,那就很容易了,就像这样:

WebResource resource = client.resource("http://myfirstUrl");
 resource.addFilter(new LoggingFilter());
 Form form = new Form();
 form.add("grant_type", "authorization_code");
 form.add("client_id", "myclientId");
 form.add("client_secret", "mysecret");
 form.add("code", "mycode");
 form.add("redirect_uri", "http://mysecondUrl");       
 String msg = resource.accept(MediaType.APPLICATION_JSON).post(String.class, form);

然后我可以得到我想要的消息。

但是在Play框架中,我找不到任何发送此类帖子请求的库。我相信这应该是一个非常简单的功能,Play应该集成它。我试图搜索并发现大多数用例都是关于表格的视图。谁能给我一些帮助或例子?提前谢谢!

1 个答案:

答案 0 :(得分:4)

您可以使用Play WS API在Play应用程序中进行异步HTTP调用。首先,您应该添加javaWs作为依赖项。

libraryDependencies ++= Seq(
  javaWs
)

然后发出HTTP POST请求就像这样简单;

WS.url("http://myposttarget.com")
 .setContentType("application/x-www-form-urlencoded")
 .post("key1=value1&key2=value2");

post()和其他http方法返回一个F.Promise<WSResponse>对象,这是从Play Scala继承到Play Java的东西。基本上它是异步调用的基础机制。您可以按如下方式处理并获取请求的结果:

Promise<String> promise = WS.url("http://myposttarget.com")
 .setContentType("application/x-www-form-urlencoded")
 .post("key1=value1&key2=value2")
 .map(
    new Function<WSResponse, String>() {
        public String apply(WSResponse response) {
            String result = response.getBody();
            return result;
        }
    }
);

最后获得的promise对象是我们案例中String对象的包装器。你可以将包裹的String作为:

long timeout = 1000l;// 1 sec might be too many for most cases!
String result = promise.get(timeout);

timeout是等待此异步请求被视为失败的等待时间。

有关更详细的说明和更高级的用例,请查看文档和javadoc。

https://www.playframework.com/documentation/2.3.x/JavaWS

https://www.playframework.com/documentation/2.3.x/api/java/index.html