feikiss
feikiss

Reputation: 354

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

Currently I'm switching to play framework to develop but I'm new to this wonderful framework. I just want to send a post request to remote server and get response.

If I use Jersey, it would be quite easy, just like this:

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

and then I can get the msg which is what I want.

But in Play framework, I cannot find any libs to send such post request. I believe this should be a very simple feature and Play should have integrated it. I've tried to search and found most use case are about the Form in view leve. Could anyone give me some help or examples? Thanks in advance!

Upvotes: 3

Views: 8141

Answers (1)

ysf
ysf

Reputation: 4874

You can use Play WS API for making asynchronous HTTP Calls within your Play application. First you should add javaWs as a dependency.

libraryDependencies ++= Seq(
  javaWs
)

Then making HTTP POST Requests are as simple as;

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

post() and other http methods returns a F.Promise<WSResponse> object which is something inherited from Play Scala to Play Java. Basically it is the underlying mechanism of asynchronous calls. You can process and get the result of your request as follows:

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;
        }
    }
);

Finally obtained promise object is a wrapper around a String object in our case. And you can get the wrapped String as:

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

timeout is the waiting time until this asynchronous request will be considered as failed.

For much more detailed explanation and more advanced use cases checkout the documentation and javadocs.

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

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

Upvotes: 4

Related Questions