8

我需要使用spray框架发出一个简单的 HTTP 请求。我在他们的网站上找到了一些示例,但结果证明它们很复杂并且涉及 Akka,这对我来说不是必需的。

此外,我需要能够填写请求的标头(如X-Applicationcontent-type等),当然还有请求的 post 数据(在我的例子中,它是 JSON 格式的数据)。

那么我该怎么做呢?

4

1 回答 1

13

这是一个例子。将会有少量的 akka 代码,但正如我在评论中提到的,喷雾是必要的:

import spray.httpx.RequestBuilding._
import spray.http._
import HttpMethods._
import HttpHeaders._
import MediaTypes._
import spray.json._
import DefaultJsonProtocol._
import spray.httpx.SprayJsonSupport._
import akka.actor.ActorSystem
import spray.io.IOExtension
import akka.actor.Props
import spray.can.client.HttpClient
import spray.client.HttpConduit
import scala.concurrent.Future
import scala.util.Failure
import scala.util.Success

case class MyObj(str:String, i:Int)

object SprayExample {
  implicit val myObjFormat = jsonFormat2(MyObj)

  def main(args: Array[String]) {
    import concurrent.ExecutionContext.Implicits._

    val obj = MyObj("hello", 1)   
    val req = Post("/some/url", obj) ~> addHeader("X-Foo", "bar")

    implicit val system = ActorSystem()
    val ioBridge = IOExtension(system).ioBridge()
    val httpClient = system.actorOf(Props(new HttpClient(ioBridge)))

    val conduit = system.actorOf(
      props = Props(new HttpConduit(httpClient, "localhost", 8080)),
      name = "http-conduit"
    )

    val pipeline = HttpConduit.sendReceive(conduit)
    val response: Future[HttpResponse] = pipeline(req)
    response onComplete{
      case Failure(ex) => ex.printStackTrace()
      case Success(resp) => println("success: " + resp.status)
    }
  }
}

我的构建文件如下所示:

scalaVersion := "2.10.0"

resolvers ++= Seq(
  "Scala Tools Repo Releases" at "http://scala-tools.org/repo-releases",
  "Typesafe Repo Releases" at "http://repo.typesafe.com/typesafe/releases/",
  "spray" at "http://repo.spray.io/"
)


libraryDependencies ++= Seq(
  "io.spray" % "spray-httpx" % "1.1-M7",
  "io.spray" % "spray-client" % "1.1-M7",
  "com.typesafe.akka" %% "akka-actor" % "2.1.0",
  "io.spray" %%  "spray-json" % "1.2.5"
)
于 2013-06-09T11:21:44.383 回答