2016-08-05 6 views
1

Akka HTTP 클라이언트를 사용하여 REST 웹 서비스에 GET 요청을 보내려고합니다.Akka Http 클라이언트가 HttpRequest에서 쿠키를 설정합니다.

내가 GET을하기 전에 요청에 쿠키를 설정하는 방법을 알 수 없습니다.

웹을 검색하여 서버 측에서 쿠키를 읽을 수있는 방법을 찾았습니다. 하지만 클라이언트 측 요청에서 쿠키를 설정하는 방법을 알려주는 것을 찾지 못했습니다. 내 자신의 연구를 바탕으로

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

에 쿠키를 설정하려면 다음 방법을 시도하지만이

[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

가 나가는 헤더해야 오류를 '쿠키 (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)) 
3

akka-http 클라이언트의 헤더를 구성하는 관용적 인 방법은 0123입니다.은 akka.http.scaladsl.model.headers을 사용합니다. 귀하의 경우에는

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