Created
March 30, 2011 03:07
-
-
Save xuwei-k/893786 to your computer and use it in GitHub Desktop.
scalaでhttp POST をする場合の最低限のサンプル
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.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 | |
} |
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.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