Michael Michael - 1 year ago 133
HTTP Question

Synchronous HTTP call in Scala

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.

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

library ?

Answer Source

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)

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

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

And use it like

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}")
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download