攻城狮科学家

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

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));
}
}
posted on 2016-01-11 16:46  攻城狮科学家  阅读(564)  评论(0编辑  收藏  举报