ScalaにはHTTPインタラクションを簡単に扱うためのDispatchライブラリというのがあります。
このライブラリを使えば非常に小さなコードでHTTPアクセスを実現できますが、implicit definitionやなぞの演算子や記号クラスを使っているために少し慣れが必要になります。
また、単純な通信だけでなく、twitter,google,oauthなどの便利機能も備えています。(2011/07/03時点(v 0.8.3))
ネタ記録庫/Scala/dispatch/セットアップ?
import dispatch.Http
import dispatch.Request
import scala.io.Source
object HelloDispatch {
def main(args: Array[String]) : Unit = {
wget("http://proofcafe.org/index.html") {
source =>
val lines = source.getLines()
lines.foreach(println)
}
}
def wget[T](uri : String)(callback : Source => T) : T = {
val http = new Http()
val req = new Request(uri)
http(req >~ callback)
}
}
ソースコードおよびbuild.sbtはこちら https://github.com/yoshihiro503/hello_dispatch
実行
$ sbt run
使用するモジュールは以下の二つです。
project/build.scalaはこんな感じ。
... libraryDependencies ++= Seq ( ... "net.databinder" %% "dispatch-http" % "0.8.5", "net.databinder" %% "dispatch-http-json" % "0.8.5" ) ...
shorten関数の型は String => String として定義。つまりurlを文字列で渡すと短縮urlを文字列で返す。以下のように非常に小さいコードで実現できます。しかし慣れないと意味がわからないので以下に解説します。IDとKEYのところにはBitlyアカウントのそれを当てはめましょう。
import dispatch._
import dispatch.json.JsHttp._
def shorten(url: String): String = {
val http = new Http()
val req = :/("api.bitly.com")/"v3"/("shorten?login=[ID]&apiKey=[KEY]&longUrl="+url+"&format=json")
http(req ># 'data ? ('url ? str))
}
使用している記号とメソッドの対応
注意点
以上をふまえて、暗黙の変換やimportなどをいっさい省略せずに使わずに同じコードを書くと以下のようになる。
import dispatch.Http
import dispatch.:/
import dispatch.Request
import dispatch.json.JsHandlers
import dispatch.json.JsHttp
def shorten(url: String): String = {
val http = new Http()
val req : Request =
Request.toRequestVerbs(
Request.toRequestVerbs((:/.apply("api.bitly.com")))./("v3")
)./("shorten?login=[ID]&apiKey=[KEY]&longUrl="+url+"&format=json")
http.apply(
JsHttp.requestToJsHandlers(req).>#(
JsHttp.ext2fun(
JsHttp.sym_add_operators('data).?(
JsHttp.sym_add_operators('url).?(JsHttp.str)(JsHttp.ctx)
)(JsHttp.ctx)
)
)
)
}