我不熟悉在其中使用 Play Framework 和 WSClient。我在尝试时遇到了问题。
我使用 WS.url("urlhere").withHeaders("Cookie -> cookieIuse").get() 创建了一个请求
根据该调用的响应,我使用 cookie 调用并检查了 cookie 数组的大小,但它最终为 0!
我确保请求正确传递,确实如此!我的代码应该用 cookie 响应,因为我使用 withCookies 返回 cookie。有任何想法吗?我已经测试了我的代码并遵循了它,一切都是正确的,除了没有来自 withCookies 的 cookie 或 header 被返回到 WSResponse。
谢谢
最佳答案
WS.url("urlhere").withHeaders("Cookie -> cookieIuse")
,它将 cookie 设置到请求中,而不是响应中。如果你想从响应中获取cookie,你应该在你的 Controller 中将cookie设置为响应,而不是使用以下代码的请求。
response().setCookie("Cookie", "cookieIuse");
引用在这里https://www.playframework.com/documentation/2.5.x/JavaResponse
另外,如果“urlhere”不是您自己的网站url,您无权操作响应,该响应由服务器端返回,也只能在服务器端修改。
更新:
给你举个例子,下面是scala代码,java就是这样
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")
}
}
在上面的示例中,'test' Action 将使用 WS 调用 'index'。 'index' 返回带有 Cookie 的响应,'test' 使用 response.cookies 获取响应中的所有 cookies
祝你好运。
关于java - Play WSResponse 没有来自 WSRequest 的 cookie 或 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37264792/