Skip to content

Instantly share code, notes, and snippets.

@jeff-r
Created November 29, 2015 23:05
Show Gist options
  • Save jeff-r/36e67fd9cc99b8431c11 to your computer and use it in GitHub Desktop.
Save jeff-r/36e67fd9cc99b8431c11 to your computer and use it in GitHub Desktop.
Get the content of a web request
import org.apache.http.client.methods.{CloseableHttpResponse, HttpGet}
import org.apache.http.impl.client.HttpClientBuilder
import scala.util.Try
class RestClient {
def getRestContent(url:String): Try[String] = {
val client = HttpClientBuilder.create.build
val result = Try( {
val request = new HttpGet(url)
val response = client.execute(request)
val entity = response.getEntity
var content = ""
if (entity != null) {
val inputStream = entity.getContent
content = io.Source.fromInputStream(inputStream).getLines.mkString
inputStream.close
}
client.close
content
} )
return result
}
}
import scala.util.{Failure, Success}
object RestClientApp extends App {
def ping = {
val client = new RestClient
client.getRestContent("http://localhost:4567") match {
case Success(result) => println(result)
case Failure(error) => println(s"failed with error: '${error.getMessage}'")
}
client.getRestContent("http://localhost:9000") match {
case Success(result) => println(result)
case Failure(error) => println(s"failed with error: '${error.getMessage}'")
}
}
ping
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment