以喷雾方式发送发帖请求 [英] Sending a post request in spray

查看:129
本文介绍了以喷雾方式发送发帖请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

此外,我需要能够填写请求的标头(如X-Applicationcontent-type等),当然还要填写请求的发布数据(在我的情况下,它将是JSON中的数据)

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

那我该怎么做?

推荐答案

这里是一个示例.将会有少量的Akka代码,但是正如我在评论中提到的那样,有必要进行喷雾:

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

我的构建文件如下:

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

这篇关于以喷雾方式发送发帖请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆