Sending a post request in spray

Alan Coromano picture Alan Coromano · Jun 9, 2013 · Viewed 8.9k times · Source

I need to make a simple HTTP request using spray framework. I found some examples on their web site but they turned out to be complicated and involving Akka which is not necessary for me.

Besides, I need to be able to fill in a request's headers (like X-Application, content-type, etc) and, of course, a requests's post data (in my case, it would be a data in JSON).

So how do I do that?

Answer

cmbaxter picture cmbaxter · Jun 9, 2013

Here is an example. There is going to be a small amount of akka code but as I mentioned in my comment, it's necessary for spray:

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)
    }
  }
}

My build file looks like this:

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"
)