John Doe John Doe - 1 month ago 23
Scala Question

Send POST request with parameters in body via Play WS API

Currently, I am sending get requests via the Play WS API as follows:

wsClient
.url(myUrl)
.withQueryString(getParams(): _*)
.get()


Now I want to change this call to use HTTP Post. When calling the following:

wsClient
.url(myUrl)
.withMethod("POST")
.withBody(getParams(): _*)
.get()


I receive the following error:


Cannot write an instance of Seq[(String, String)] to HTTP response. Try to define a Writeable[Seq[(String, String)]]


I guess it's because the method
getParams
returns
Seq[(String, String)]
.

How can I fix this?

Answer

When using http post key value pairs are sent using content type application/x-www-form-urlencoded

Here is the code for posting

 client.url(myUrl)
    .withHeaders("Content-type" -> "application/x-www-form-urlencoded")
    .post(getParams.map { case (k, v) => s"$k=$v"}.mkString("&"))