This repository has been archived by the owner on Apr 4, 2022. It is now read-only.
/
Http.scala
257 lines (200 loc) · 9.08 KB
/
Http.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
package scalaj.http
import java.net.{HttpURLConnection, URL, URLEncoder, URLDecoder}
import java.io.{DataOutputStream, InputStream, BufferedReader, InputStreamReader, ByteArrayOutputStream}
import org.apache.commons.codec.binary.Base64
import javax.net.ssl.HttpsURLConnection
import javax.net.ssl.SSLContext
import javax.net.ssl.SSLSession
import javax.net.ssl.SSLSocketFactory
import javax.net.ssl.TrustManager
import javax.net.ssl.X509TrustManager
import javax.net.ssl.HostnameVerifier
import java.security.cert.X509Certificate
object HttpOptions {
type HttpOption = HttpURLConnection => Unit
def method(method: String):HttpOption = c => c.setRequestMethod(method)
def connTimeout(timeout: Int):HttpOption = c => c.setConnectTimeout(timeout)
def readTimeout(timeout: Int):HttpOption = c => c.setReadTimeout(timeout)
def allowUnsafeSSL:HttpOption = c => c match {
case httpsConn: HttpsURLConnection =>
val hv = new HostnameVerifier() {
def verify(urlHostName: String, session: SSLSession) = true
}
httpsConn.setHostnameVerifier(hv)
val trustAllCerts = Array[TrustManager](new X509TrustManager() {
def getAcceptedIssuers: Array[X509Certificate] = null
def checkClientTrusted(certs: Array[X509Certificate], authType: String){}
def checkServerTrusted(certs: Array[X509Certificate], authType: String){}
})
val sc = SSLContext.getInstance("SSL")
sc.init(null, trustAllCerts, new java.security.SecureRandom())
httpsConn.setSSLSocketFactory(sc.getSocketFactory())
case _ => // do nothing
}
def sslSocketFactory(sslSocketFactory: SSLSocketFactory): HttpOption = c => c match {
case httpsConn: HttpsURLConnection =>
httpsConn.setSSLSocketFactory(sslSocketFactory)
case _ => // do nothing
}
}
object MultiPart {
def apply(name: String, filename: String, mime: String, data: String): MultiPart = MultiPart(name, filename, mime, data.getBytes(Http.charset))
}
case class MultiPart(val name: String, val filename: String, val mime: String, val data: Array[Byte])
case class HttpException(val code: Int, val message: String, val body: String) extends RuntimeException(code + ": " + message)
object Http {
def apply(url: String):Request = get(url)
type HttpExec = (Request, HttpURLConnection) => Unit
type HttpUrl = Request => URL
object Request {
def apply(exec: HttpExec, url: HttpUrl, method:String):Request = Request(method, exec, url, Nil, Nil, HttpOptions.method(method)::defaultOptions)
}
case class Request(method: String, exec: HttpExec, url: HttpUrl, params: List[(String,String)], headers: List[(String,String)], options: List[HttpOptions.HttpOption]) {
def params(p: (String, String)*):Request = params(p.toList)
def params(p: List[(String,String)]):Request = Request(method, exec,url, p, headers,options)
def headers(h: (String,String)*):Request = headers(h.toList)
def headers(h: List[(String,String)]):Request = Request(method,exec,url, params, h,options)
def param(key: String, value: String):Request = Request(method,exec,url,(key,value)::params, headers,options)
def header(key: String, value: String):Request = Request(method,exec,url,params, (key,value)::headers,options)
def options(o: HttpOptions.HttpOption*):Request = options(o.toList)
def options(o: List[HttpOptions.HttpOption]):Request = Request(method,exec, url, params, headers, o)
def option(o: HttpOptions.HttpOption):Request = Request(method,exec,url, params, headers,o::options)
def auth(user: String, password: String) = header("Authorization", "Basic " + base64(user + ":" + password))
def oauth(consumer: Token):Request = oauth(consumer, None, None)
def oauth(consumer: Token, token: Token):Request = oauth(consumer, Some(token), None)
def oauth(consumer: Token, token: Token, verifier: String):Request = oauth(consumer, Some(token), Some(verifier))
def oauth(consumer: Token, token: Option[Token], verifier: Option[String]):Request = OAuth.sign(this, consumer, token, verifier)
def getUrl: URL = url(this)
def apply[T](parser: InputStream => T): T = process((conn:HttpURLConnection) => tryParse(conn.getInputStream(), parser))
def process[T](processor: HttpURLConnection => T): T = {
url(this).openConnection match {
case conn:HttpURLConnection =>
conn.setInstanceFollowRedirects(true)
headers.reverse.foreach{case (name, value) =>
conn.setRequestProperty(name, value)
}
options.reverse.foreach(_(conn))
exec(this, conn)
try {
processor(conn)
} catch {
case e: java.io.IOException =>
throw new HttpException(conn.getResponseCode, conn.getResponseMessage, tryParse(conn.getErrorStream(), readString))
}
}
}
def responseCode = process((conn:HttpURLConnection) => conn.getResponseCode)
def asBytes = apply(readBytes)
def asString = apply(readString)
def asXml = apply(is => scala.xml.XML.load(is))
def asParams: List[(String,String)] = {
asString.split("&").flatMap(_.split("=") match {
case Array(k,v) => Some(urlDecode(k), urlDecode(v))
case _ => None
}).toList
}
def asParamMap = Map(asParams:_*)
def asToken = {
val params = asParamMap
Token(params("oauth_token"), params("oauth_token_secret"))
}
}
def tryParse[E](is: InputStream, parser: InputStream => E):E = try {
parser(is)
} finally {
is.close
}
/**
* [lifted from lift]
*/
def readString(is: InputStream) = {
val in = new InputStreamReader(is, charset)
val bos = new StringBuilder
val ba = new Array[Char](4096)
def readOnce {
val len = in.read(ba)
if (len > 0) bos.append(ba, 0, len)
if (len >= 0) readOnce
}
readOnce
bos.toString
}
/**
* [lifted from lift]
* Read all data from a stream into an Array[Byte]
*/
def readBytes(in: InputStream): Array[Byte] = {
val bos = new ByteArrayOutputStream
val ba = new Array[Byte](4096)
def readOnce {
val len = in.read(ba)
if (len > 0) bos.write(ba, 0, len)
if (len >= 0) readOnce
}
readOnce
bos.toByteArray
}
val defaultOptions = List(HttpOptions.connTimeout(30000), HttpOptions.readTimeout(60000))
def urlEncode(name: String): String = URLEncoder.encode(name, charset)
def urlDecode(name: String): String = URLDecoder.decode(name, charset)
def base64(bytes: Array[Byte]) = new String(Base64.encodeBase64(bytes))
def base64(in: String): String = base64(in.getBytes(charset))
def toQs(params: List[(String,String)]) = params.map(p => urlEncode(p._1) + "=" + urlEncode(p._2)).mkString("&")
def appendQs(url:String, params: List[(String,String)]) = url + (if(params.isEmpty) "" else {
(if(url.contains("?")) "&" else "?") + toQs(params)
})
def appendQsHttpUrl(url: String): HttpUrl = r => new URL(appendQs(url, r.params))
def noopHttpUrl(url :String): HttpUrl = r => new URL(url)
def get(url: String): Request = {
val getFunc: HttpExec = (req,conn) => conn.connect
Request(getFunc, appendQsHttpUrl(url), "GET")
}
val CrLf = "\r\n"
val Pref = "--"
val Boundary = "gc0pMUlT1B0uNdArYc0p"
def multipart(url: String, parts: MultiPart*): Request = {
val postFunc: Http.HttpExec = (req,conn) => {
conn.setDoOutput(true)
conn.setDoInput(true)
conn.setUseCaches(false)
conn.setRequestMethod("POST")
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + Boundary)
conn.setRequestProperty("MIME-Version", "1.0")
val out = new DataOutputStream(conn.getOutputStream())
req.params.foreach {
case (name, value) =>
out.writeBytes(Pref + Boundary + CrLf)
out.writeBytes("Content-Disposition: form-data; name=\"" + name + "\"")
out.writeBytes(CrLf + CrLf + value.toString + CrLf)
}
parts.foreach { part =>
out.writeBytes(Pref + Boundary + CrLf)
out.writeBytes("Content-Disposition: form-data; name=\"" + part.name + "\"; filename=\"" + part.filename + "\"" + CrLf)
out.writeBytes("Content-Type: " + part.mime + CrLf + CrLf)
out.write(part.data)
out.writeBytes(CrLf + Pref + Boundary + Pref + CrLf)
}
out.flush()
out.close()
}
Http.Request(postFunc, Http.noopHttpUrl(url), "POST")
}
def postData(url: String, data: String): Request = postData(url, data.getBytes(charset))
def postData(url: String, data: Array[Byte]): Request = {
val postFunc: HttpExec = (req,conn) => {
conn.setDoOutput(true)
conn.connect
conn.getOutputStream.write(data)
}
Request(postFunc, noopHttpUrl(url), "POST")
}
def post(url: String): Request = {
val postFunc: HttpExec = (req,conn) => {
conn.setDoOutput(true)
conn.connect
conn.getOutputStream.write(toQs(req.params).getBytes(charset))
}
Request(postFunc, noopHttpUrl(url), "POST").header("content-type", "application/x-www-form-urlencoded")
}
val charset = "UTF-8"
}