Skip to content

Instantly share code, notes, and snippets.

@piotrga
Created March 24, 2013 20:00
Show Gist options
  • Save piotrga/5233282 to your computer and use it in GitHub Desktop.
Save piotrga/5233282 to your computer and use it in GitHub Desktop.
The simplest Async Scala Http Client for 2.10
import concurrent.{Await, ExecutionContext, Future}
import java.net.{HttpURLConnection, URL}
import io.Source
import concurrent.duration.FiniteDuration
case class HttpResponse(code : Int, body: String, headers: Map[String, List[String]])
case class RequestBody(body: String, contentType: String = "text/plain")
object RequestBody{
implicit def toRB(json: String) = RequestBody(json, contentType = "application/json")
}
class Http(baseUrl : String, cookie: Option[String] = None)(implicit ec: ExecutionContext, encoding: String="UTF-8"){
def setCookie(cookie: String) = {
new Http(baseUrl, Some(cookie))
}
import collection.JavaConverters._
def get(path : String ) : Future[HttpResponse] = doRequest("GET", path)
def post(path : String, requestBody: RequestBody ) : Future[HttpResponse] = doRequest("POST", path, Option(requestBody))
def put(path : String, requestBody: RequestBody ) : Future[HttpResponse] = doRequest("PUT", path, Option(requestBody))
def delete(path : String ) : Future[HttpResponse] = doRequest("DELETE", path)
def doRequest(method: String, path: String, requestBody: Option[RequestBody] = None): Future[HttpResponse] = Future {
val con = new URL(baseUrl + path).openConnection().asInstanceOf[HttpURLConnection]
try {
con.setDoInput(true)
con.setInstanceFollowRedirects(false)
cookie.foreach(cookie => con.setRequestProperty("Cookie", cookie))
con.setRequestMethod(method)
requestBody foreach{ requestBody=>
con.setRequestProperty("Content-Type", s"${requestBody.contentType}; charset=$encoding")
con.setDoOutput(true)
val out = con.getOutputStream
out.write(requestBody.body.getBytes(encoding))
out.flush()
out.close()
}
val headers = con.getHeaderFields.asScala.mapValues(_.asScala.toList).toMap - null
val body = Source.fromInputStream(con.getInputStream).getLines() mkString ("\n")
HttpResponse(con.getResponseCode, body, headers)
} finally {
con.disconnect()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment