Skip to content

Instantly share code, notes, and snippets.

@alun
Last active December 17, 2015 01:39
Show Gist options
  • Save alun/5530174 to your computer and use it in GitHub Desktop.
Save alun/5530174 to your computer and use it in GitHub Desktop.
import java.io.{UnsupportedEncodingException, InputStreamReader, IOException}
import java.net.{ProtocolException, MalformedURLException, HttpURLConnection, URL}
import util.control.Exception._
object URLPrinter extends App {
val defaultEncoding = "CP1251"
val targetURL = "http://google.com"
var readerOpt = Option.empty[InputStreamReader]
val catchingErrors = Seq(
classOf[MalformedURLException],
classOf[IOException],
classOf[ProtocolException],
classOf[UnsupportedEncodingException]
)
catching(catchingErrors: _*).andFinally {
// finally close the input reader
allCatch.opt {
readerOpt.map(_.close())
}
} .either {
val u = new URL(targetURL)
val con = u.openConnection().asInstanceOf[HttpURLConnection]
con.setRequestMethod("GET")
con.connect()
val enc = Option(con.getContentEncoding).getOrElse(defaultEncoding)
readerOpt = Some(new InputStreamReader(con.getInputStream, enc))
readerOpt.map { reader =>
val buf = Array.ofDim[Char](4048)
reader.read(buf)
print(buf.mkString(""))
}
} .left.map { e =>
e.printStackTrace()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment