【问题标题】:Setting a cookie for HTTP POST in Scala with Dispatch使用 Dispatch 在 Scala 中为 HTTP POST 设置 cookie
【发布时间】:2013-10-24 20:22:14
【问题描述】:

我似乎无法使用 Dispatch 设置 cookie。服务器重新发送一个新的会话 ID,这意味着我尝试发送的会话 ID 没有以正确的方式发送。代码如下:

val domain = "myhost.com"
val host_req = host(domain).secure
val request = host_req / "path" / "path"

def post = request << Map("key" -> "SomeValue")

val response: Either[Throwable, Map[String, String]] =
    Http(post OK asHeaders).either()

//The cookie comes down in the form "Set-Cookie: SESSIONID=<somesession>; Path=/path/; HttpOnly"

//successfully retrieves the session id...
val sessionId = getSessionId(response)
println(sessionId)
val sessionCookie = new com.ning.http.client.Cookie(domain, "SESSIONID", sessionId, "/path/", -1, true)

request.POST.addCookie(sessionCookie)
def establishPost = request << Map("key" -> "SomeValue")
establishPost.addCookie(sessionCookie)

val establishResponse: Either[Throwable, Map[String, String]] =
    Http(establishPost OK asHeaders).either()


//Server sends down new SESSIONID...
//sessionId != getSEssionId(establishPost)

这是使用最新版本的 Dispatch。我正在尝试学习 Scala,而我唯一不知道该怎么做的就是在作为请求发送之前检查establishPost 对象的标头。

【问题讨论】:

    标签: scala post cookies scala-dispatch


    【解决方案1】:

    这样应该会更好:

    def reqWithParams = request << Map("key" -> "SomeValue")
    val reqWithCookies = reqWithParams.addCookie(sessionCookie)
    

    addCookie 方法返回新对象(带有 cookie 的对象),但您的代码没有使用它。

    【讨论】:

    • 这似乎是确定设置cookie的问题。您能否回答第二部分关于我将如何检查 POST 请求的内容以便将其与已知的有效 POST 进行比较的问题?
    • 这绝对可以解决问题。
    • 关于检查请求对象:最简单的方法就是在日志中打印出来。它定义了以下方法:host、creds、method、path、headers、body、defaultCharset。正文的类型为Option[org.apache.http.HttpEntity],标题为List[(String, String)]。我建议从 github 下载调度发行版:github.com/dispatch/dispatch 并检查代码,这绝对很有启发性:)
    • 在使用 sbt 重新制作 eclipse 项目后,我终于有了一些智能感知。我遇到的问题是 println(mypost) 产生了“Req()”。 Intellisense 向我展示了一个 toRequest() 方法,然后我可以执行 println(mypost.toRequest) 并且它显示了一些有用的东西。
    • 假装它直到你成功 :) 一开始很混乱,只要给它几个月的时间,继续阅读并尝试理解其他人编写的代码,你会变得更好:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-26
    • 2016-01-10
    • 1970-01-01
    • 2013-09-13
    • 2017-03-10
    • 2012-08-21
    相关资源
    最近更新 更多