2016-08-05 65 views
1

我正在尝试使用Akka Http客户端向REST Web服务发出GET请求。Akka Http客户端在HttpRequest上设置Cookie

我无法弄清楚如何在进行GET之前在请求上设置cookie。

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

根据我自己的研究,我尝试了以下方法来设置HTTP请求

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() 
     } 
    } 
} 

一个cookie但是这给出了一个错误

[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 
+0

'设置Cookie'是响应头。对于请求标题,请使用标题名称“Cookie”(请参阅​​https://en.wikipedia.org/wiki/HTTP_cookie#Setting_a_cookie)。 – devkat

回答

1

输出头必须是“曲奇”而不是' 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)) 
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, ...))