繁体   English   中英

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

[英]play framework- how to send post request using java code in play framework

目前我正在转向开发框架来开发,但我是这个奇妙框架的新手。 我只想向远程服务器发送一个帖子请求并获得响应。

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

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框架中,我找不到任何libs来发送这样的帖子请求。 我相信这应该是一个非常简单的功能,Play应该集成它。 我试图搜索并发现大多数用例都是关于视图级别的表单。 谁能给我一些帮助或例子? 提前致谢!

您可以使用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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM