A Scala "open URL as InputStream" method (HttpURLConnection)

As a quick note, I just found this getUrlInputStream method in an old Scala project. It needs to be updated and cleaned-up, but if you are looking for some code to get you started with opening a URL as an InputStream in Scala, this may be helpful:

/**
 * See http://alvinalexander.com/blog/post/java/how-open-url-read-contents-httpurl-connection-java
 *
 * Note that this can throw a java.net.UnknownHostException
 *
 */
def getUrlInputStream(url: String,
                     connectTimeout: Int = 5000,
                     readTimeout: Int = 5000,
                     requestMethod: String = "GET") = {
   val u = new URL(url)
   val conn = u.openConnection.asInstanceOf[HttpURLConnection]
   HttpURLConnection.setFollowRedirects(false)
   conn.setConnectTimeout(connectTimeout)
   conn.setReadTimeout(readTimeout)
   conn.setRequestMethod(requestMethod)
   conn.connect
   conn.getInputStream
}

Again, the code isn’t great, but it can serve as a starter if you need some code to read from a URL as an input stream in Scala.