来自Scala的REST调用

时间:2016-07-07 09:34:16

标签: scala rest

如何在HTTP上从一个Scala项目到其他scala项目API进行REST调用。它们可能是POST或GET,带有Json格式的请求参数。

2 个答案:

答案 0 :(得分:3)

使用JSON的完整示例(使用akka 2.4.4和spray json):

class Test (implicit actorSystem: ActorSystem) extends DefaultJsonProtocol {
  private implicit val exampleFormat = jsonFormat2(Example)

  private implicit val materializer = ActorMaterializer()

  val endpoint = "http://api.example.com/abc"

  private case class Example(var1: Int, var2: String)

  private def createRequest(example: Example): HttpRequest =
    HttpRequest(
      method = HttpMethods.POST,
      uri = endpoint,
      entity = HttpEntity(ContentTypes.`application/json`, example.toJson.toString),
      headers = Seq()
    )

  Http().singleRequest(createRequest(Example(213, "test"))
}

进口:

import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.model._
import akka.stream.ActorMaterializer
import scala.concurrent.Future
import spray.json.DefaultJsonProtocol
import scala.collection.immutable.Seq
import scala.concurrent.ExecutionContext.Implicits.global

答案 1 :(得分:2)