2016-08-05 4 views
1

Akka Http Clientを使用してREST WebサービスにGETリクエストを作成しようとしています。Akka HttpクライアントがHttpRequestでCookieを設定する

私はGETを行う前に、リクエストにクッキーを設定する方法を理解できません。

ウェブを検索したところ、サーバー側で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() 
     } 
    } 
} 

にクッキーを設定するには、次のアプローチを試みたが、これはエラーに

[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クライアントのヘッダーを構成する慣習的な方法は、0123ですを使用してください。akka.http.scaladsl.model.headers。あなたのケースでは

それは

val cookieHeader = akka.http.scaladsl.model.headers.Cookie("name","value") 
HttpRequest(uri = Uri("/comments"), headers = List(cookieHeader, ...)) 
関連する問題