Scala中的同步HTTP调用 [英] Synchronous HTTP call in Scala

查看:221
本文介绍了Scala中的同步HTTP调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要执行一个同步HTTP POST调用:使用一些数据创建HTTP Post请求,连接到服务器,发送请求,接收响应,然后关闭连接.释放用于执行此调用的所有资源很重要.

I need to perform a single synchronous HTTP POST call: create an HTTP Post request with some data, connect to the server, send the request, receive the response, and close the connection. It is important to release all resources used to do this call.

现在,我正在Java中使用Apache Http Client进行操作.如何使用Scala dispatch库完成此操作?

Now I am doing it in Java with Apache Http Client. How can I do it with Scala dispatch library ?

推荐答案

类似的方法应该可以工作(虽然尚未进行测试)

Something like this should work (haven't tested it though)

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

(对于此示例,我正在使用 https://github.com/dispatch/reboot )

(I'm using https://github.com/dispatch/reboot for this example)

您明确地等待将来的结果,这可能是String还是异常.

You explicitly wait for the result of the future, which is either a String or an exception.

并像使用它

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

这篇关于Scala中的同步HTTP调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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