2013-12-19 25 views

回答

1

我不會nk有一個簡單的方法可以用Scala的標準庫來實現。但還有其他幾個圖書館可以幫助你解決問題。

我給你一個解釋,說明如何用Spray做到這一點。此解決方案具有無阻塞的優點,但由於您是Scala的新用戶,因此使用Future可能對您而言是新的。

首先,您需要爲項目添加一些依賴關係。最簡單的方法是如果你使用SBT。將以下行添加到您的build.sbt

resolvers += "spray repo" at "http://repo.spray.io" 

// Dependencies 
libraryDependencies += "com.typesafe.akka" %% "akka-actor" % "2.2.3" 

libraryDependencies += "io.spray" % "spray-client" % "1.2.0" 

現在你的程序的源代碼看起來很容易的,也是不可阻擋:

import akka.actor.ActorSystem 
import spray.http._ 
import spray.client.pipelining._ 
import scala.concurrent.Future 
import scala.util.{ Success, Failure } 

object HTTPTest extends App { 
    implicit val system = ActorSystem("http-test") 
    import system.dispatcher // execution context for futures 

    // take an http request and return a future of http response 
    val pipeline: HttpRequest => Future[HttpResponse] = sendReceive 


    // this method will give you *only* the status code for a URL as a Future 
    def getStatusFor(url: String): Future[Int] = 
    pipeline(Get(url)).map { x => x.status.intValue } 

    // use it this way 
    getStatusFor("http://server.org/help").onComplete { 
    case Success(statusCode) => println(statusCode) 
    case Failure(err) => // do something with the exception 
    } 
} 

這是否幫助?

2

由於URL只是對Web資源的虛擬引用,它始終有效。 ;)

此外,你可以閱讀從資源文本一行:

try { 
    val text = Source.fromUrl(new java.net.URL(someString)).getLine 
} catch { 
    case java.io.IOException => // do something ... 
} 

或讀取資源文本的所有行:

​​

或者您可以使用Java類連接到資源並閱讀它的長度等...:

try { 
    val connection = (new java.net.URL(someString)).openConnection 
    connection.connect; 
    val l = connection.getContentLength 
    // use the connection anyway you like 
} catch { 
    case java.io.IOException => // do something ... 
} 
+0

在這裏,它給出了頁面的html代碼。它工作正常:)有沒有辦法檢查** HTML respose代碼(404)**檢查網址? – Shashika

+0

'scala.io.Source'不適合您的問題。它不會讓你訪問HTTP頭。 – pvorb

2

您將需要使用http訪問l試圖訪問該URL。使用play2的WS

import play.api.libs.ws.WS 
val futureResponse:Future[Response] = WS.url("http://www.example.com/404.html").get() 

那麼您可以使用一元操作讀取響應和反應

futureResponse.map {response => response.status==404} //will return a Future[Boolean] 

,或者你可以阻止,直到你真正擁有的響應:

import scala.concurrent._ 
import scala.concurrent.duration._ 

val response =Await.result(futureResponse, 5 seconds) 
if(response.status==404) { 
    ??? 
}else{ 
    ??? 
} 

有其他HTTP客戶端爲斯卡拉如Dispatch

相關問題