MrTugay
MrTugay

Reputation: 21

Play WSResponse does not have the cookies or headers from WSRequest

I am new to using the Play Framework and WSClient within it. I have encountered a problem while trying.

I created a request with WS.url("urlhere").withHeaders("Cookie -> cookieIuse").get()

With the Response from that call I use the cookies call and checked the size of the Array of cookies but it ended up being 0!

I made sure the request was passing through correctly and it was! My code should have responded with cookies since I used the withCookies to return cookies. Any ideas? I have tested my code and followed it and everything is correct except that none of the cookies or headers from withCookies are being returned to the WSResponse.

Thanks

Upvotes: 1

Views: 1041

Answers (1)

Jerry
Jerry

Reputation: 492

WS.url("urlhere").withHeaders("Cookie -> cookieIuse")

,which sets the cookie into the request, not in response. If you want to get cookie from response, you should set the cookie into response in your controller, not the request using the following code.

response().setCookie("Cookie", "cookieIuse");

the reference is here https://www.playframework.com/documentation/2.5.x/JavaResponse

Another thing is that, if the "urlhere" is not your own website url, you have no rights to operate the response, which is returned by the server end and also only can be modified in server end.

update:

give some example for you , the scala code is following and the java just looks like it

class Application @Inject() (ws: WSClient) extends Controller {

implicit val context = play.api.libs.concurrent.Execution.Implicits.defaultContext

def index = Action { implicit request =>
    //get all contents from request header including cookies set in 'test' controller 
    //and turn it to map
    val requestCookies = request.headers.toSimpleMap 

    //print the cookies in the request send from 'test' controller
    println(requestCookies)

    Ok(views.html.index("Your new application is ready.")).withCookies(Cookie("theme", "blue"))
}

def test = Action { implicit request =>
    //method 'withHeaders' sets the cookies into request 
    //and send it to 'index' controller
    val futureResponse: Future[WSResponse] = ws.url("http://localhost:9000/").withHeaders("cookie" -> "test").get()

    futureResponse.map {
    //get cookie from WSResponse, the response is the type of WSResponse after mapped
    response => response.cookies.foreach(println(_)) 

    }
    Ok("test")
 }
}

in the example above, 'test' Action will call 'index' with WS. The 'index' return the response with Cookies and 'test' uses the response.cookies to get all the cookies in response

Good luck with you.

Upvotes: 1

Related Questions