Skip to content

Instantly share code, notes, and snippets.

@jilen
Last active August 29, 2015 14:27
Show Gist options
  • Save jilen/9e47d1c0a70f94323229 to your computer and use it in GitHub Desktop.
Save jilen/9e47d1c0a70f94323229 to your computer and use it in GitHub Desktop.
import com.ning.http.client._
import com.ning.http.client.cookie.Cookie
import scala.concurrent._
object http {
private val rng = new scala.util.Random
implicit class AhcClientOps(cli: AsyncHttpClient) {
def asyncExec(request: Request) = {
val p = Promise[Response]()
cli.executeRequest(request ,new AsyncCompletionHandler[Response] {
override def onCompleted(response: Response) = {
p.success(response)
response
}
override def onThrowable(t: Throwable){
p.failure(t)
}
})
p.future
}
}
implicit class ResponseOps(val response: Response) {
def body = response.getResponseBody()
}
implicit class RequestBuilderOps(val builder: RequestBuilder) {
def withCookies(cookies: Iterable[Cookie]) = {
cookies.foldLeft(builder)(_.addCookie(_))
}
def withRandProxies(proxies: Seq[ProxyServer]) = {
if(proxies.nonEmpty)
builder.setProxyServer(proxies(rng.nextInt(proxies.size)))
else builder
}
}
def get(url: String) = {
new RequestBuilder().setUrl(url).setMethod("GET")
}
def post(url: String) = {
new RequestBuilder().setUrl(url).setMethod("POST")
}
}
import com.ning.http.client._
val cli = new AsyncHttpClient
val foo = cli.asyncExec(http.get("http://foo.com").build()).map(_.body.toInt)
val abc = cli.asyncExec(http.get("http://abc.xyz").build()).map(_.body.toInt)
val fa: Future[(Int, Int)] = for {
f <- foo
a <- abc
} yield (f, a)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment