我需要使用spray
框架发出一个简单的HTTP请求。我在他们的网站上发现了一些例子,但事实证明它们很复杂并且涉及Akka,这对我来说并不是必需的。
此外,我需要能够填写请求的标题(如X-Application
,content-type
等),当然还有请求的帖子数据(在我的情况下,它将是一个JSON中的数据。)
那我该怎么做?
答案 0 :(得分: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"
)