Created
March 7, 2012 12:16
-
-
Save shinobu-aoki/1992773 to your computer and use it in GitHub Desktop.
scala-ioのURLからの読込でUser-Agentを設定するimplicit conversion
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.net.URL | |
import scalax.io.{CloseAction, InputStreamResource, KnownName} | |
import scalax.io.JavaConverters.AsInput | |
// User-Agentを設定するimplicit conversion | |
object URLConverter { | |
implicit def asInputConverter(url: URL)(implicit userAgent: UserAgent) = | |
new AsInput(new InputStreamResource({ | |
val conn = url.openConnection | |
conn.setRequestProperty("User-Agent", userAgent.ua) | |
conn.getInputStream | |
}, CloseAction.Noop, () => None, KnownName(url.toExternalForm))) | |
} | |
case class UserAgent(val ua: String) | |
// sizeFuncでNoneを返すようにする事で、対象のURLに一度だけアクセスするようにしている | |
// ※scalax.io.JavaConverters内のimplicit conversionは二度アクセスしてしまう(二度目はサイズ取得) | |
// new URL("http://www.scala-lang.org").asInput.bytes.force |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment