Željko Trogrlić
Željko Trogrlić

Reputation: 2895

POST request using spray-client

I want to send XML over HTTP POST request to server using spray-client with some headers set etc. However, only examples that I can find are for JSON requests.

Can somebody provide a simple snippet of code for XML over HTTP POST communication using spray-client?

Thanks!

Upvotes: 0

Views: 4987

Answers (2)

flurdy
flurdy

Reputation: 3972

With a hacky way to be specific about the content type. Note payload can be string or xml literal.

import spray.client.pipelining._
import spray.http._

val pipeline: HttpRequest => Future[HttpResponse] = {
   addHeader("My-Header-Key", "myheaderdata") ~>
   ((_:HttpRequest).mapEntity( _.flatMap( f => HttpEntity( 
      f.contentType.withMediaType(MediaTypes.`application/xml`),f.data)))) 
     ~> sendReceive
}

pipeline(
  Post(
     "http://www.example.com/myendpoint", <MyXmlTag>MyXmlData</MyXmlTag>
  )
)

Upvotes: 0

cmbaxter
cmbaxter

Reputation: 35443

Here is a small code sample for creating a spray HttpRequest that has an xml NodeSeq based payload. Let me know if you this helps or if you need more code (like submitting the request):

import spray.httpx.RequestBuilding._
import spray.http._
import HttpMethods._
import HttpHeaders._
import MediaTypes._

object SprayXml {
  def main(args: Array[String]) {
    val xml = <root>foo</root>
    val req = Post("/some/url", xml)
  }
}

The two dependencies I was using to make this code work are spray-client and spray-httpx.

The relevant pieces from my build.sbt are:

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

Upvotes: 4

Related Questions