-
Notifications
You must be signed in to change notification settings - Fork 125
/
OkHttpNetworkAdapter.kt
45 lines (35 loc) · 1.54 KB
/
OkHttpNetworkAdapter.kt
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
package net.dean.jraw.http
import okhttp3.*
/**
* [NetworkAdapter] implementation backed by Square's fantastic [OkHttp](https://square.github.io/okhttp/)
*/
class OkHttpNetworkAdapter @JvmOverloads constructor(
/** The value of the User-Agent header sent with every request */
override var userAgent: UserAgent,
/** A customized OkHttpClient instance. Defaults to a default client. */
private val http: OkHttpClient = OkHttpClient()
) : NetworkAdapter {
override fun execute(r: HttpRequest): HttpResponse {
return HttpResponse(createCall(r).execute())
}
override fun connect(url: String, listener: WebSocketListener): WebSocket {
val client = OkHttpClient()
val ws = client.newWebSocket(Request.Builder()
.get()
.url(url)
.build(), listener)
// Shutdown the ExecutorService so this program can terminate normally
client.dispatcher().executorService().shutdown()
return ws
}
private fun createCall(r: HttpRequest): Call =
(if (r.basicAuth != null) createAuthenticatedClient(r.basicAuth) else http).newCall(compileRequest(r))
private fun createAuthenticatedClient(data: BasicAuthData): OkHttpClient =
http.newBuilder().authenticator(BasicAuthenticator(data)).build()
private fun compileRequest(r: HttpRequest): Request =
Request.Builder()
.headers(r.headers.newBuilder().set("User-Agent", userAgent.value).build())
.url(r.url)
.method(r.method, r.body)
.build()
}