By Alvin Alexander. Last updated: November 10, 2016
Here's a simple way to get content from a REST web service using Scala:
object GetUrlContent extends App { val url = "http://api.hostip.info/get_json.php?ip=12.215.42.19" val result = scala.io.Source.fromURL(url).mkString println(result) }
That's a simple, "new" way I do it with Scala. However, note that it handles timeouts very poorly, such as if the web service you're calling is down or running slowly.
FWIW, here's an old approach I used to retrieve REST content (content from a REST URL):
/** * Returns the text content from a REST URL. Returns a blank String if there * is a problem. (Probably should use Option/Some/None; I didn't know about it * back then.) */ def getRestContent(url:String): String = { val httpClient = new DefaultHttpClient() val httpResponse = httpClient.execute(new HttpGet(url)) val entity = httpResponse.getEntity() var content = "" if (entity != null) { val inputStream = entity.getContent() content = io.Source.fromInputStream(inputStream).getLines.mkString inputStream.close } httpClient.getConnectionManager().shutdown() return content }
This function just returns the content as a String, and then you can extract whatever you need from the String once you have it.
I don't have time to condense all my content right now, but if you search the website for other REST examples, you'll see how to properly handle timeouts when calling a REST web service.