setContentType(“application/x-www-form-urlencoded”

2019-09-03 17:50发布

问题:

I am trying to invoke web service but in play framework 2.0.x i am unable to invoke any web service which is encoded.

I have looked into code:

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&param2=bar").map(
            new F.Function<WS.Response, Result>() {
                public Result apply(WS.Response response) {
                   return ok(response.toString());
                }
            }
        )
    );
}

reference: https://stackoverflow.com/a/14938117/4410109

i have tried the above code on play framework 2.0.8 but i am getting this error:

error: cannot find symbol .setContentType("application/x-www-form-urlencoded; charset=utf-8")

is there any way to set content type in play framework 2.0.8. ?

thanks

EDIT:

here is my code:

Promise<WS.Response> result2 = WS.url("desired-url")
            .setQueryParameter("sUsername","test")
            .setQueryParameter("sPwd","hbl@1234")
            .setQueryParameter("sMobileno","03332560744")
            .setQueryParameter("sTransaction_id","asdfasdfasdfasdfasdf")
            .setQueryParameter("sMessage","test")
            .post("content");

         WS.Response rs = result2.get();

it returns me invalid format error. and i have also tried it from REST Client with form-data and with same parameters, it also returns me same error "Invalid Format". but when i tried it with x-www-form-urlencoded it returns the desired result. but in play 2.0 i cant set the the content Type.

thanks

回答1:

If you POST a Map[String, Seq[String]] the content type will be set to application/x-www-form-urlencoded correctly.

.post(Map("param1" -> Seq("foo"), "param2" -> Seq("bar")))


回答2:

Seems the "setContentType" method is available from 2.1.0.

In 2.0.8 you can just set the header

public static Result wsAction() {
return async(
    play.libs.WS.url(Play.application().configuration()
        .getString("sms.service.url"))
        .setHeader(Http.HeaderNames.CONTENT_TYPE, "application/x-www-form-urlencoded; charset=utf-8")                       
        .post("param1=foo&param2=bar").map(
            new F.Function<WS.Response, Result>() {
                public Result apply(WS.Response response) {
                   return ok(response.toString());
                }
            }
        )
    );
}

Some information from play! Doc.



回答3:

In play 2.0 you can do

response().setContentType("application/x-www-form-urlencoded; charset=utf-8");
return ok(response.toString());