如何在HTTP
上从一个Scala项目到其他scala项目API进行REST调用。它们可能是POST或GET,带有Json格式的请求参数。
答案 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)
我建议使用Akka HTTP客户端(http://doc.akka.io/docs/akka/2.4.7/scala/http/client-side/index.html)
VS2013
对于JSON支持,您可以使用Spray: