Scala URL FAQ: How do I download the contents of a URL to a String or file in Scala?
I ran a few tests last night in the Scala REPL to see if I could think of different ways to download the contents of a URL to a String or file in Scala, and came up with a couple of different solutions, which I'll share here.
Download URL contents to a String in Scala
The simplest way I could think of to download the contents of a URL to a String looks like this:
import scala.io.Source val html = Source.fromURL("http://google.com") val s = html.mkString println(s)
If you really want to impress your friends and relatives, you can shorten that to one line, like this:
println(scala.io.Source.fromURL("http://google.com").mkString)
That seems like the most direct and "Scala like" approach to the problem.
Download the contents of a URL to a file
If you want to download the contents of a URL directly to a file, you can do so like this:
import sys.process._ import java.net.URL import java.io.File new URL("http://google.com") #> new File("Output.html") !!
As you can see, most of that code involves importing the packages you need, and then the last line of code actually downloads the URL contents and saves it to a file named Output.html.
If you're not used to the syntax of that last line, please see my tutorial on how to execute system commands in Scala.
Other approaches
Please note that there are other approaches and industrial-strength open source libraries to make HTTP requests, but for simple needs, these approaches may work for you.