我需要执行单个同步HTTP POST调用:使用一些数据创建HTTP Post请求,连接到服务器,发送请求,接收响应以及关闭连接.释放用于执行此调用的所有资源非常重要.
现在我使用Apache Http Client在Java中完成它.如何使用Scala dispatch库?
这样的东西应该工作(虽然没有测试过)
import dispatch._, Defaults._
import scala.concurrent.Future
import scala.concurrent.duration._
def postSync(path: String, params: Map[String, Any] = Map.empty): Either[java.lang.Throwable, String] = {
val r = url(path).POST << params
val future = Http(r OK as.String).either
Await.result(future, 10.seconds)
}
Run Code Online (Sandbox Code Playgroud)
(我在这个例子中使用https://github.com/dispatch/reboot)
您明确地等待未来的结果,即结果String或异常.
并使用它
postSync("http://api.example.com/a/resource", Map("param1" -> "foo") match {
case Right(res) => println(s"Success! Result was $res")
case Left(e) => println(s"Woops, something went wrong: ${e.getMessage}")
}
Run Code Online (Sandbox Code Playgroud)