Skip to content

Instantly share code, notes, and snippets.

@lovesh
Last active August 29, 2015 14:01
Show Gist options
  • Save lovesh/b0ac583754d2fc2edcba to your computer and use it in GitHub Desktop.
Save lovesh/b0ac583754d2fc2edcba to your computer and use it in GitHub Desktop.
Http request wrapper build with scalaj-http
import scalaj.http._
case class httpResponse(code: Int, body: String, url: String)
object httpRequest {
val options = Map(
"connTimeout" -> 5000,
"readTimeout" -> 5000
)
private def makeOptionList(options: Map[String, Any]): List[HttpOptions.HttpOption] = {
val requestOptions = this.options ++ options
List(
HttpOptions.connTimeout(requestOptions("connTimeout").asInstanceOf[Int]),
HttpOptions.readTimeout(requestOptions("readTimeout").asInstanceOf[Int])
)
}
private def makeResponse(request: Http.Request): httpResponse = {
if (request.responseCode > 199 && request.responseCode < 400)
httpResponse(request.responseCode, request.asString, request.getUrl.toString)
else
httpResponse(request.responseCode, "", request.getUrl.toString)
}
def get(url: String, params: Map[String, Any] = Map(), options: Map[String, Any] = Map()): httpResponse = {
val optionList = makeOptionList(options)
val requestParams = params map { case (k,v) => (k, v.toString)}
val request: Http.Request = Http(url).options(optionList).params(requestParams)
makeResponse(request)
}
def post(url: String, params: Map[String, Any] = Map(), options: Map[String, Any] = Map()): httpResponse = {
val optionList = makeOptionList(options)
val requestParams = params map { case (k,v) => (k, v.toString)}
val request: Http.Request = Http.post(url).options(optionList).params(requestParams)
makeResponse(request)
}
}
@hoffrocket
Copy link

Each call to .responseCode actually creates a new request. You probably want something like this:

try {
  val (code: Int, header: Map[String, List[String]], body: String) = request.asHeadersAndParse(Http.readString)
  HttpResponse(code, body)
} catch {
  case HttpException(code: Int, message: String, body: String, cause: Throwable) => HttpResponse(code, body)
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment