Spray-client Rest

原创
2015/08/26 14:40
阅读数 85

1.sbt import

"io.spray" %% "spray-client" % "1.3.1",
"io.spray" %% "spray-can" % "1.3.2",
"io.spray" %% "spray-routing" % "1.3.2"

a.Get request

import spray.client.pipelining._
import spray.http._
import scala.concurrent._
import akka.actor.{ActorSystem, Props}

import scala.concurrent.ExecutionContext.Implicits.global
import scala.util._
implicit val system = ActorSystem()

val pipeline: HttpRequest => Future[HttpResponse] = sendReceive

val response: Future[HttpResponse] = pipeline(Get("http://tiku.huatu.com/apis/cascalog/logs/mod_user_log"))
response.onComplete {
  case Failure(t) =>
    println(s"error $t")
  case Success(r) =>
    println(s"success ${r.status}")
    println(r.entity.asString)
}

b.Post request

case class User(id: Option[Int], username: String)
implicit val orderConfirmationFormat = jsonFormat2(User)   // extends DefaultJsonProtocol
mport spray.client.pipelining._
import spray.http._
import scala.concurrent._
import akka.actor.{ActorSystem}
import scala.concurrent.ExecutionContext.Implicits.global
import scala.util._
implicit val system = ActorSystem()

import spray.httpx.SprayJsonSupport._  //重要
val pipeline: HttpRequest => Future[User] =   sendReceive ~> unmarshal[User]
val response: Future[User] = pipeline { Post("http://localhost:8088/users", User(Option(100),"jiang"))}
  response.onComplete{
    case Failure(t) =>
      println(s"error $t")
    case Success(r) =>
      println(s"success ${r}")
      println(r)
  }

完整代码请参考Gist Code


展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
在线直播报名
返回顶部
顶部