java - Play WSResponse 没有来自 WSRequest 的 cookie 或 header

标签 java http cookies playframework playframework-2.0

我不熟悉在其中使用 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/

相关文章:

Java 控制台键盘 - 自动接受输入

http - 如何使用 curl 以 UTF-8 编码发布表单数据?

javascript - AngularJS 无法从 PHP 获取 HTTP header

ruby-on-rails - 在站点之间共享 session 数据?

javascript - 子域读取和删除主域cookie

java - 如何从不同的 Activity 类设置 onclicklistener?

java - 在Android Studio中生成失败

java - 图片上传到服务器的php错误响应= httpclient.execute(httppost);

http - Boost beast websocket 服务器异步接受失败,缓冲区溢出

ruby - ruby 中的 curl 请求