Last active
December 17, 2015 01:39
-
-
Save alun/5530174 to your computer and use it in GitHub Desktop.
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 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