HttpRequest上的Akka Http客户端集Cookie

时间:2016-08-05 15:27:49

标签: scala cookies akka-http

我正在尝试使用Akka Http Client向REST Web服务发出GET请求。

在制作GET之前,我无法弄清楚如何在请求上设置cookie。

我搜索了网络,我找到了在服务器端读取cookie的方法。但我找不到任何能告诉我如何在客户端请求中设置cookie的内容。

根据我自己的研究,我尝试了以下方法在http请求上设置cookie

import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.model._
import akka.http.scaladsl.unmarshalling.Unmarshal
import akka.stream.scaladsl.{Sink, Source}
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
import akka.http.scaladsl.model.headers.HttpCookie
import akka.stream.ActorMaterializer
import spray.json._

import scala.util.{Failure, Success}

case class Post(postId: Int, id: Int, name: String, email: String, body: String)

trait JsonSupport extends SprayJsonSupport with DefaultJsonProtocol {
   implicit val postFormat = jsonFormat5(Post.apply)
}

object AkkaHttpClient extends JsonSupport{
   def main(args: Array[String]) : Unit = {
      val cookie = headers.`Set-Cookie`(HttpCookie(name="foo", value="bar"))
      implicit val system = ActorSystem("my-Actor")
      implicit val actorMaterializer = ActorMaterializer()
      implicit val executionContext = system.dispatcher
      val mycookie = HttpCookie(name="foo", value="bar")
      val httpClient = Http().outgoingConnection(host = "jsonplaceholder.typicode.com")
      val request = HttpRequest(uri = Uri("/comments"), headers = List(cookie))
      val flow = Source.single(request)
         .via(httpClient)
         .mapAsync(1)(r => Unmarshal(r.entity).to[List[Post]])
         .runWith(Sink.head)

      flow.andThen {
         case Success(list) => println(s"request succeded ${list.size}")
         case Failure(_) => println("request failed")
      }.andThen {
         case _ => system.terminate()
      }
   }
}

但这会产生错误

[WARN] [08/05/2016 10:50:11.134] [my-Actor-akka.actor.default-dispatcher-3] [akka.actor.ActorSystemImpl(my-Actor)] 
HTTP header 'Set-Cookie: foo=bar' is not allowed in requests

2 个答案:

答案 0 :(得分:3)

为akka-http客户端构造任何标头的惯用方法是 使用akka.http.scaladsl.model.headers

在你的情况下,它将是

val cookieHeader = akka.http.scaladsl.model.headers.Cookie("name","value")
HttpRequest(uri = Uri("/comments"), headers = List(cookieHeader, ...))

答案 1 :(得分:1)

传出标题必须是' Cookie'不是' Set-Cookie':

      val cookie = HttpCookiePair("foo", "bar")
      val headers: immutable.Seq[HttpHeader] = if (cookies.isEmpty) immutable.Seq.empty else immutable.Seq(Cookie(cookies))
      val request = HttpRequest(uri = uri).withHeadersAndEntity(headers, HttpEntity(msg))