Play framework - how to send post request using java code in game system

I am currently moving to a development platform, but I am new to this wonderful framework. I just want to send a request to a remote server and get a response.

If I use Jersey it will be pretty 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 I want.

But on the Play platform, I cannot find any libraries to send such a post request. I believe this should be a very simple function and Play should have integrated it. I tried searching and found that most of the use cases are form in view. Can anyone give me any help or examples? Thanks in advance!

+3


source to share


1 answer


You can use the Play WS API to make asynchronous HTTP calls in your Play app. You must add javaWs

as dependency first.

libraryDependencies ++= Seq(
  javaWs
)

      

Then making HTTP POST requests is as simple as:

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

      

post()

and other http methods return an object F.Promise<WSResponse>

which is something Play Scala inherited for Java rendering. This is basically the main mechanism for asynchronous calls. You can process and get the result of your request like this:

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, the resulting promise

object is a wrapper around the object String

in our case. And you can get wrapped String

like:

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

      

timeout

- time to wait until this asynchronous request is considered unsuccessful.

For a more detailed explanation and more advanced use cases check out 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

+4


source







All Articles