Last active
August 29, 2015 14:01
-
-
Save lovesh/b0ac583754d2fc2edcba to your computer and use it in GitHub Desktop.
Http request wrapper build with scalaj-http
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Each call to .responseCode actually creates a new request. You probably want something like this: