码迷,mamicode.com
首页 > Web开发 > 详细

scala: How to write a simple HTTP GET request client in Scala (with a timeout)

时间:2016-01-11 17:50:45      阅读:230      评论:0      收藏:0      [点我收藏+]

标签:

Scala CookBook: http://scalacookbook.com/

@throws(classOf[java.io.IOException])
@throws(classOf[java.net.SocketTimeoutException])
def get(url: String,
        connectTimeout:Int =5000,
        readTimeout:Int =5000,
        requestMethod: String = "GET") = {
    import java.net.{URL, HttpURLConnection}
    val connection = (new URL(url)).openConnection.asInstanceOf[HttpURLConnection]
    connection.setConnectTimeout(connectTimeout)
    connection.setReadTimeout(readTimeout)
    connection.setRequestMethod(requestMethod)
    val inputStream = connection.getInputStream
    val content = io.Source.fromInputStream(inputStream).mkString
    if (inputStream != null) inputStream.close
    content
}

if want to set the request property, add:
for (header <- headers) {
val headerDetails = header.split(":")
if (headerDetails.size<=2) {
connection.setRequestProperty(headerDetails(0), headerDetails(1));
}
}

scala: How to write a simple HTTP GET request client in Scala (with a timeout)

标签:

原文地址:http://www.cnblogs.com/dataclimber/p/scala.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!