使用spray-client发出POST请求

时间:2013-05-20 13:32:56

标签: scala post spray spray-client

我想使用带有一些标头设置的spray-client将HTTP over HTTP POST请求发送到服务器。但是,我只能找到可用于JSON请求的示例。

有人可以使用spray-client为HTTP over HTTP POST通信提供简单的代码片段吗?

谢谢!

2 个答案:

答案 0 :(得分:4)

以下是一个小代码示例,用于创建具有基于xml HttpRequest的有效负载的喷雾NodeSeq。如果您对此有所帮助,或者您需要更多代码(例如提交请求),请告诉我们:

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

我用来使这段代码工作的两个依赖项是spray-clientspray-httpx

我的build.sbt中的相关部分是:

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

答案 1 :(得分:0)

使用hacky方式来具体了解内容类型。注意有效负载可以是字符串或xml文字。

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