Skip to content
This repository

Simple scala wrapper for HttpURLConnection. OAuth included.

branch: master

Build Status

Simple Http

This is a bare bones http client for scala which wraps HttpURLConnection



val scalaj_http = "org.scalaj" %% "scalaj-http" % "0.3.14"




Simple Get

import scalaj.http.Http


Immutable Request

Http(url) is just shorthead for a Http.apply which returns an immutable instance of Http.Request.
You can create a Request and reuse it:

val request: Http.Request = Http("")

val resultOne = request.asString
val resultTwo = request.asString

Additive Request

All the "modification" methods of a Request are actually returning a new instance. The param(s), option(s), header(s) methods always add to their respective sets. So calling .headers(newHeaders) will return a Request instance that has newHeaders appended to the previous req.headers

Simple Post"").params("name" -> "jon", "age" -> "29").asString

OAuth v1 Dance and Request

import scalaj.http.{Http, Token}

val consumer = Token("key", "secret")
val token ="").param("oauth_callback","oob")

println("Go to" + token.key)

val verifier = Console.readLine("Enter verifier: ").trim

val accessToken ="")
  .oauth(consumer, token, verifier).asToken

println(Http("").oauth(consumer, accessToken).asString)

Parsing the response

Http("").{responseCode, asString, asXml, asBytes, asParams}

Advanced Usage Examples

Parse the response InputStream to JSON

import net.liftweb.json.JsonParser

Http(""){inputStream => 
  JsonParser.parse(new InputStreamReader(inputStream))

Post raw Array[Byte] or String data and get response code

Http.postData(url, data).header("content-type", "application/json").responseCode

Post multipart/form-data

Http.multipart(url, MultiPart("photo", "headshot.png", "image/png", fileBytes)).responseCode

You can also stream uploads and get a callback on progress:

Http.multipart(url, MultiPart("photo", "headshot.png", "image/png", inputStream, bytesInStream, 
  lenWritten => {
    println("Wrote %d bytes out of %d total for headshot.png".format(lenWritten, bytesInStream))

Send https request to site with self-signed or otherwise shady certificate


Do a HEAD request


Custom connect and read timeouts

These are set to 100 and 500 milliseconds respectively by default


Get responseCode, responseHeaders and parsedResponse

val (responseCode, headersMap, resultString) = Http(url).asHeadersAndParse(Http.readString)

Get request via a proxy

val response = Http(url).proxy(proxyHost, proxyPort).asString

Other custom options

The .option() method takes a function of type HttpURLConnection => Unit so you can manipulate the connection in whatever way you want before the request executes.

Change the Charset

By default, the charset for all param encoding and string response parsing is UTF-8. You can override with charset of your choice:

Something went wrong with that request. Please try again.