Skip to content

Instantly share code, notes, and snippets.

@shinobu-aoki
Created March 7, 2012 12:16
Show Gist options
  • Save shinobu-aoki/1992773 to your computer and use it in GitHub Desktop.
Save shinobu-aoki/1992773 to your computer and use it in GitHub Desktop.
scala-ioのURLからの読込でUser-Agentを設定するimplicit conversion
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