2014-01-30 38 views
3

我無法通過http代理從scala中的URL讀取。Scala的Source.fromURL通過http代理

我有這樣的代碼

//This is just to print the environment 
import scala.collection.JavaConversions._ 
println(System.getProperties.filter(_._1 startsWith("http")).toList sortBy(_._1) mkString "\n") 

import scala.io.Source 
val html = Source.fromURL("http://google.com") 
val s = html.mkString 
println(s) 

我收到以下錯誤

(http.proxyHost,158.169.9.13) 
(http.proxyPassword,*****) 
(http.proxyPort,8012) 
(http.proxyUser,*****) 
java.io.IOException: Server returned HTTP response code: 407 for URL: http://google.com 
     at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1612) 
     at java.net.URL.openStream(URL.java:1035) 
     at scala.io.Source$.fromURL(Source.scala:143) 
     at scala.io.Source$.fromURL(Source.scala:133) 
     at Main$$anon$1.<init>(download.scala:7) 
     at Main$.main(download.scala:1) 
     at Main.main(download.scala) 

我期待google.com的頁面源代碼的打印。

回答

1

你試過Source.fromURL(新的java.net.URL(「myURL」))API嗎?代碼看起來沿着這些線:

val response: String = try { 
     val proxy: Proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("10.0.0.1", 8080)) 
     val connection: HttpURLConnection = new java.net.URL("myURL").openConnection(proxy).asInstanceOf[HttpURLConnection] 
     connection.connect() 
     Source.fromInputStream(connection.getInputStream).getLines.mkString 
    } 
    catch { 
     case e: Throwable => "" // Do whatever you want here: logging/throw exception/.. 
    }