15.9. Creating a Simple GET Request Client
Problem
You want an HTTP client you can use to make GET
request calls.
Solution
There are many potential solutions to this problem. This recipe demonstrates three approaches:
A simple use of the
scala.io.Source.fromURL
methodAdding a timeout wrapper around
scala.io.Source.fromURL
to make it more robustUsing the Apache HttpClient library
These solutions are demonstrated in the following sections.
A simple use of scala.io.Source.fromURL
If it doesn’t matter that your web service client won’t time out in a controlled manner, you can use this simple method to download the contents from a URL:
/**
* Returns the text (content) from a URL as a String.
* Warning: This method does not time out when the service is non-responsive.
*/
def
get
(
url
:
String
)
=
scala
.
io
.
Source
.
fromURL
(
url
).
mkString
This GET
request method lets
you call the given RESTful URL to retrieve its content. You can use it
to download web pages, RSS feeds, or any other content using an HTTP
GET
request.
Under the covers, the Source.fromURL
method uses classes like
java.net.URL
and java.io.InputStream
, so this method can
throw exceptions that extend from java.io.IOException
. As a result, you may
want to annotate your method to indicate that:
@throws
(
classOf
[
java.io.IOException
])
def
get
(
url
:
String
)
=
io
.
Source
.
fromURL
(
url
).
mkString
Setting the timeout while using scala.io.Source.fromURL
As mentioned, that simple solution suffers from a significant problem: it doesn’t time out if the URL you’re ...
Get Scala Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.