Created
November 29, 2015 23:05
-
-
Save jeff-r/36e67fd9cc99b8431c11 to your computer and use it in GitHub Desktop.
Get the content of a web request
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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