/
HurlStack.kt
262 lines (230 loc) · 8.8 KB
/
HurlStack.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
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
258
259
260
261
262
/*
* Copyright (C) 2022 panpf <panpfpanpf@outlook.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.panpf.sketch.http
import androidx.annotation.WorkerThread
import com.github.panpf.sketch.request.ImageRequest
import java.io.IOException
import java.io.InputStream
import java.net.HttpURLConnection
import java.net.URL
import javax.net.ssl.HttpsURLConnection
/**
* Use [HttpURLConnection] to request HTTP
*/
class HurlStack private constructor(
/**
* Read timeout, in milliseconds
*/
val readTimeoutMillis: Int = HttpStack.DEFAULT_TIMEOUT,
/**
* Connection timeout, in milliseconds
*/
val connectTimeoutMillis: Int = HttpStack.DEFAULT_TIMEOUT,
/**
* HTTP UserAgent
*/
val userAgent: String? = null,
/**
* HTTP header
*/
val headers: Map<String, String>? = null,
/**
* Repeatable HTTP headers
*/
val addHeaders: List<Pair<String, String>>? = null,
/**
* Callback before executing connection
*/
val onBeforeConnect: ((url: String, connection: HttpURLConnection) -> Unit)? = null,
/**
* Enabled tls protocols
*/
val enabledTlsProtocols: Array<String>? = null
) : HttpStack {
@WorkerThread
@Throws(IOException::class)
override fun getResponse(request: ImageRequest, url: String): HttpStack.Response {
var newUri = url
while (newUri.isNotEmpty()) {
val connection = (URL(newUri).openConnection() as HttpURLConnection).apply {
this@apply.connectTimeout = this@HurlStack.connectTimeoutMillis
this@apply.readTimeout = this@HurlStack.readTimeoutMillis
doInput = true
if (this@HurlStack.userAgent != null) {
setRequestProperty("User-Agent", this@HurlStack.userAgent)
}
if (!addHeaders.isNullOrEmpty()) {
for ((key, value) in addHeaders) {
addRequestProperty(key, value)
}
}
if (!headers.isNullOrEmpty()) {
for ((key, value) in headers) {
setRequestProperty(key, value)
}
}
request.httpHeaders?.apply {
addList.forEach {
addRequestProperty(it.first, it.second)
}
setList.forEach {
setRequestProperty(it.first, it.second)
}
}
val enabledTlsProtocols = enabledTlsProtocols
if (this is HttpsURLConnection && enabledTlsProtocols?.isNotEmpty() == true) {
sslSocketFactory = TlsCompatSocketFactory(enabledTlsProtocols)
}
}
onBeforeConnect?.invoke(url, connection)
// Currently running on a limited number of IO contexts, so this warning can be ignored
connection.connect()
val code = connection.responseCode
if (code == 301 || code == 302 || code == 307) {
newUri = connection.getHeaderField("Location")
} else {
return HurlResponse(connection)
}
}
throw IOException("Unable to get response")
}
override fun toString(): String =
"HurlStack(connectTimeout=${connectTimeoutMillis},readTimeout=${readTimeoutMillis},userAgent=${userAgent})"
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as HurlStack
if (readTimeoutMillis != other.readTimeoutMillis) return false
if (connectTimeoutMillis != other.connectTimeoutMillis) return false
if (userAgent != other.userAgent) return false
if (headers != other.headers) return false
if (addHeaders != other.addHeaders) return false
if (onBeforeConnect != other.onBeforeConnect) return false
return true
}
override fun hashCode(): Int {
var result = readTimeoutMillis
result = 31 * result + connectTimeoutMillis
result = 31 * result + (userAgent?.hashCode() ?: 0)
result = 31 * result + (headers?.hashCode() ?: 0)
result = 31 * result + (addHeaders?.hashCode() ?: 0)
result = 31 * result + (onBeforeConnect?.hashCode() ?: 0)
return result
}
private class HurlResponse(private val connection: HttpURLConnection) : HttpStack.Response {
@get:Throws(IOException::class)
override val code: Int by lazy { connection.responseCode }
@get:Throws(IOException::class)
override val message: String? by lazy { connection.responseMessage }
override val contentLength: Long by lazy {
getHeaderField("content-length")?.toLongOrNull() ?: -1
}
override val contentType: String? by lazy {
connection.contentType
}
@get:Throws(IOException::class)
override val content: InputStream
get() = connection.inputStream
override fun getHeaderField(name: String): String? {
return connection.getHeaderField(name)
}
}
class Builder {
private var connectTimeoutMillis: Int = HttpStack.DEFAULT_TIMEOUT
private var readTimeoutMillis: Int = HttpStack.DEFAULT_TIMEOUT
private var userAgent: String? = null
private var extraHeaders: MutableMap<String, String>? = null
private var addExtraHeaders: MutableList<Pair<String, String>>? = null
private var onBeforeConnect: ((url: String, connection: HttpURLConnection) -> Unit)? = null
private var enabledTlsProtocols: List<String>? = null
/**
* Set connection timeout, in milliseconds
*/
fun connectTimeoutMillis(connectTimeoutMillis: Int) = apply {
this.connectTimeoutMillis = connectTimeoutMillis
}
/**
* Set read timeout, in milliseconds
*/
fun readTimeoutMillis(readTimeoutMillis: Int): Builder = apply {
this.readTimeoutMillis = readTimeoutMillis
}
/**
* Set HTTP UserAgent
*/
fun userAgent(userAgent: String?): Builder = apply {
this.userAgent = userAgent
}
/**
* Set HTTP header
*/
fun headers(headers: Map<String, String>): Builder = apply {
this.extraHeaders = (this.extraHeaders ?: HashMap()).apply {
putAll(headers)
}
}
/**
* Set HTTP header
*/
fun headers(vararg headers: Pair<String, String>): Builder = apply {
headers(headers.toMap())
}
/**
* Set repeatable HTTP headers
*/
fun addHeaders(headers: List<Pair<String, String>>): Builder = apply {
this.addExtraHeaders = (this.addExtraHeaders ?: ArrayList()).apply {
addAll(headers)
}
}
/**
* Set repeatable HTTP headers
*/
fun addHeaders(vararg headers: Pair<String, String>): Builder = apply {
addHeaders(headers.toList())
}
/**
* Callback before executing connection
*/
fun onBeforeConnect(block: (url: String, connection: HttpURLConnection) -> Unit): Builder =
apply {
this.onBeforeConnect = block
}
/**
* Set tls protocols
*/
@Suppress("unused")
fun enabledTlsProtocols(vararg enabledTlsProtocols: String): Builder = apply {
this.enabledTlsProtocols = enabledTlsProtocols.toList()
}
/**
* Set tls protocols
*/
@Suppress("unused")
fun enabledTlsProtocols(enabledTlsProtocols: List<String>): Builder = apply {
this.enabledTlsProtocols = enabledTlsProtocols.toList()
}
fun build(): HurlStack = HurlStack(
readTimeoutMillis = readTimeoutMillis,
connectTimeoutMillis = connectTimeoutMillis,
userAgent = userAgent,
headers = extraHeaders?.takeIf { it.isNotEmpty() },
addHeaders = addExtraHeaders?.takeIf { it.isNotEmpty() },
onBeforeConnect = onBeforeConnect,
enabledTlsProtocols = enabledTlsProtocols?.toTypedArray(),
)
}
}