Skip to content

Instantly share code, notes, and snippets.

@xuwei-k
Created March 30, 2011 03:07
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xuwei-k/893786 to your computer and use it in GitHub Desktop.
Save xuwei-k/893786 to your computer and use it in GitHub Desktop.
scalaでhttp POST をする場合の最低限のサンプル
import java.io.{BufferedReader,InputStreamReader,PrintStream}
import java.net.URL
import scala.collection.mutable
// エラー処理とか全くしてないよ!
def post( url:String,header:Map[String,String] = Map() ,param:Map[String,String] = Map() ):List[String] = {
val uc = new URL(url).openConnection
uc.setDoOutput(true)
header.foreach{case (key,value) =>
uc.setRequestProperty( key , value )
}
val postStr = param.map{case (key,value) => key + "=" + value }.mkString("&")
val ps = new PrintStream(uc.getOutputStream)
ps.print(postStr)
ps.close()
val is = uc.getInputStream
val reader = new BufferedReader(new InputStreamReader(is))
var buffer = new mutable.ListBuffer[String]()
var s:String = null
while ({s = reader.readLine;s} != null) {
buffer += s
}
reader.close
buffer.toList
}
import java.io._
import java.net.URL
import scala.collection.mutable
def post( url:String,header:Map[String,String] = Map() ,param:Map[String,String] = Map() ):Seq[Byte] = {
val uc = new URL(url).openConnection
uc.setDoOutput(true)
header.foreach{case (key,value) =>
uc.setRequestProperty( key , value )
}
val postStr = param.map{case (key,value) => key + "=" + value }.mkString("&")
val ps = new PrintStream(uc.getOutputStream)
ps.print(postStr)
ps.close()
val is = uc.getInputStream
val buf = new BufferedInputStream(is)
val ite = Iterator.continually(buf.read).takeWhile(-1 !=).map{_.toByte}
new mutable.WrappedArray.ofByte(ite.toArray)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment