I\'m trying to perform a post with play.api.libs.ws.WS but I can\'t figure out how to set the params, my code:
Promise promise = WS.url(Play.
The accepted answer is wrong, or at least misleading. The code
WS.url("http://localhost:9001")
.setQueryParameter("param1", "foo")
.setQueryParameter("param2", "bar")
.post("content");
will post the string content
to http://localhost:9001/?param1=foo¶m2=bar
, which is almost certainly not what the OP wanted. What is much more likely to work is
WS.url("http://localhost:9001")
.post(Map("param1" -> Seq("foo"),
"param2" -> Seq("bar")))
which posts the form param1=foo¶m2=bar
to the the URL http://localhost:9001
, which is typically what the server wants.
Hmm I guess I should really start looking at the imports!
I accidentally used import play.api.libs.ws.WS instead of import play.libs.WS; When using play.libs.WS all the methods such as post(String string) and setContentType(String string) revealed themselves. This is how I did it:
import play.Play;
import play.libs.F;
import play.libs.WS;
public static Result wsAction() {
return async(
play.libs.WS.url(Play.application().configuration()
.getString("sms.service.url"))
.setContentType("application/x-www-form-urlencoded; charset=utf-8")
.post("param1=foo¶m2=bar").map(
new F.Function<WS.Response, Result>() {
public Result apply(WS.Response response) {
return ok(response.toString());
}
}
)
);
}
Try constructing the request like this:
WS.url("http://localhost:9001")
.setQueryParameter("param1", "foo")
.setQueryParameter("param2", "bar")
.post("content");
The method url(java.lang.String url)
returns a WS.WSRequestHolder
reference which can be used to modify the original request using chained calls to setQueryParameter.
WS.url(url)
.setContentType("application/x-www-form-urlencoded")
.post("param1=foo¶m2=bar");
This method uses an HTTP POST method to send its form request. As seen from the official documentation of Play, you should had already known of the GET method.
这种方式是使用post方式提交表单请求,见于play的官方文档,get方式的你应该已经知道了。
You need to pass in something that can be converted to serialized JSON. This works for me:
WS.url("https://www.someurl.com")
.post(JsObject(Seq("theString" -> JsString(someString))))
The sequence takes any number of JsValues which can also be nested JsObjects.
for me the best way
WS.url("http://localhost:9001")
.post(Json.toJson(ImmutableMap.of("param1", "foo", "param2", "bar")));
Map from http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/google/common/collect/ImmutableMap.html
http://code.google.com/p/guava-libraries/wiki/ImmutableCollectionsExplained