Reputation: 6679
Hi I am new to Scala and Playframework. I am getting an ajax request that is json format and I need to make another request to another server with x-www-form-urlencoded format.
I have this code in the controller
def getToken = Action.async(parse.json) { request =>
WS.url("https://api.xxxx.com/v1/yyyy")
.withHeaders(
"accept" -> "application/json",
"content-type" -> "application/x-www-form-urlencoded",
"Authorization" -> "Auth %s".format(apiKey)
).post(request.body) map { response =>
Logger.info("response from get user: " + Json.prettyPrint(response.json))
Ok("ok")
}
}
I tried different ways but I can't get this working. Maybe I should do a formatter in the model. Which would be the best way to cast the request json to a request x-www-form-urlencoded?
thank you
Upvotes: 0
Views: 1966
Reputation: 4300
You just need to pass a Map[String, Seq[String]]
to the post method.
If you have some keys and values you can easily construct such a Map
.
For instance:
WS.url(url).post(Map("key1" -> Seq("value1"), "key2" -> Seq("value2")))
As mentioned in Form Submission section of Play WS docs, if you want to submit a form you have to pass a Map[String, Seq[String]]
to the post
method.
What you are passing here, instead, is a JsValue
(because the request.body
is of type JsValue
because of the body parser type which is parser.json
). So first you have to extract the set of key/value pairs from the json object and then construct a Map[String, Seq[String]]
from it and pass it to post
method.
For example if you are sure that the json object (extracted from the request body by body parser) is a JSON Object (not an Array or String or a Numeric Value) you can construct the needed Map
easily (just for the first level key/value pairs):
def getToken = Action.async(parse.json) { request =>
import play.api.libs.json.JsObject
val json = request.body.as[JsObject]
val formParamsMap = json.value.mapValues(_.asOpt[String].toSeq)
WS.url("https://api.xxxx.com/v1/yyyy")
.withHeaders(
"accept" -> "application/json",
"content-type" -> "application/x-www-form-urlencoded",
"Authorization" -> "Auth %s".format(apiKey)
)
.post(formParamsMap) map { response =>
Ok("ok")
}
}
Upvotes: 3