首页 > Web开发 > 详细

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

时间:2016-01-11 17:47:47      阅读:237      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!