2016-07-07 77 views
0

如何使REST從一個Scala項目調用HTTP到其他Scala項目API。它們可能是使用Json格式的請求參數的POST或GET。來自Scala的REST調用

回答

3

完整的示例與JSON(使用akka 2.4.4和噴泉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 
+0

謝謝Mariusz。 – Nilesh