-
Notifications
You must be signed in to change notification settings - Fork 9.1k
/
RequestBody.kt
279 lines (253 loc) · 9.56 KB
/
RequestBody.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
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
/*
* Copyright (C) 2014 Square, Inc.
*
* 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 okhttp3
import java.io.File
import java.io.FileDescriptor
import java.io.FileInputStream
import java.io.IOException
import okhttp3.internal.chooseCharset
import okhttp3.internal.commonContentLength
import okhttp3.internal.commonIsDuplex
import okhttp3.internal.commonIsOneShot
import okhttp3.internal.commonToRequestBody
import okio.BufferedSink
import okio.ByteString
import okio.FileSystem
import okio.GzipSink
import okio.Path
import okio.buffer
import okio.source
abstract class RequestBody {
/** Returns the Content-Type header for this body. */
abstract fun contentType(): MediaType?
/**
* Returns the number of bytes that will be written to sink in a call to [writeTo],
* or -1 if that count is unknown.
*/
@Throws(IOException::class)
open fun contentLength(): Long = commonContentLength()
/** Writes the content of this request to [sink]. */
@Throws(IOException::class)
abstract fun writeTo(sink: BufferedSink)
/**
* A duplex request body is special in how it is **transmitted** on the network and
* in the **API contract** between OkHttp and the application.
*
* This method returns false unless it is overridden by a subclass.
*
* ### Duplex Transmission
*
* With regular HTTP calls the request always completes sending before the response may begin
* receiving. With duplex the request and response may be interleaved! That is, request body bytes
* may be sent after response headers or body bytes have been received.
*
* Though any call may be initiated as a duplex call, only web servers that are specially
* designed for this nonstandard interaction will use it. As of 2019-01, the only widely-used
* implementation of this pattern is [gRPC][grpc].
*
* Because the encoding of interleaved data is not well-defined for HTTP/1, duplex request
* bodies may only be used with HTTP/2. Calls to HTTP/1 servers will fail before the HTTP request
* is transmitted. If you cannot ensure that your client and server both support HTTP/2, do not
* use this feature.
*
* ### Duplex APIs
*
* With regular request bodies it is not legal to write bytes to the sink passed to
* [RequestBody.writeTo] after that method returns. For duplex requests bodies that condition is
* lifted. Such writes occur on an application-provided thread and may occur concurrently with
* reads of the [ResponseBody]. For duplex request bodies, [writeTo] should return
* quickly, possibly by handing off the provided request body to another thread to perform
* writing.
*
* [grpc]: https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md
*/
open fun isDuplex(): Boolean = commonIsDuplex()
/**
* Returns true if this body expects at most one call to [writeTo] and can be transmitted
* at most once. This is typically used when writing the request body is destructive and it is not
* possible to recreate the request body after it has been sent.
*
* This method returns false unless it is overridden by a subclass.
*
* By default OkHttp will attempt to retransmit request bodies when the original request fails
* due to any of:
*
* * A stale connection. The request was made on a reused connection and that reused connection
* has since been closed by the server.
* * A client timeout (HTTP 408).
* * A authorization challenge (HTTP 401 and 407) that is satisfied by the [Authenticator].
* * A retryable server failure (HTTP 503 with a `Retry-After: 0` response header).
* * A misdirected request (HTTP 421) on a coalesced connection.
*/
open fun isOneShot(): Boolean = commonIsOneShot()
companion object {
/**
* Returns a new request body that transmits this string. If [contentType] is non-null and lacks
* a charset, this will use UTF-8.
*/
@JvmStatic
@JvmName("create")
fun String.toRequestBody(contentType: MediaType? = null): RequestBody {
val (charset, finalContentType) = contentType.chooseCharset()
val bytes = toByteArray(charset)
return bytes.toRequestBody(finalContentType, 0, bytes.size)
}
@JvmStatic
@JvmName("create")
fun ByteString.toRequestBody(contentType: MediaType? = null): RequestBody = commonToRequestBody(contentType)
/** Returns a new request body that transmits this. */
@JvmStatic
@JvmName("create")
@ExperimentalOkHttpApi
fun FileDescriptor.toRequestBody(contentType: MediaType? = null): RequestBody {
return object : RequestBody() {
override fun contentType() = contentType
override fun isOneShot(): Boolean = true
override fun writeTo(sink: BufferedSink) {
FileInputStream(this@toRequestBody).use {
sink.buffer.writeAll(it.source())
}
}
}
}
/** Returns a new request body that transmits this. */
@JvmOverloads
@JvmStatic
@JvmName("create")
fun ByteArray.toRequestBody(
contentType: MediaType? = null,
offset: Int = 0,
byteCount: Int = size,
): RequestBody = commonToRequestBody(contentType, offset, byteCount)
/** Returns a new request body that transmits the content of this. */
@JvmStatic
@JvmName("create")
fun File.asRequestBody(contentType: MediaType? = null): RequestBody {
return object : RequestBody() {
override fun contentType() = contentType
override fun contentLength() = length()
override fun writeTo(sink: BufferedSink) {
source().use { source -> sink.writeAll(source) }
}
}
}
/** Returns a new request body that transmits the content of this. */
@JvmStatic
@JvmName("create")
@ExperimentalOkHttpApi
fun Path.asRequestBody(
fileSystem: FileSystem,
contentType: MediaType? = null,
): RequestBody {
return object : RequestBody() {
override fun contentType() = contentType
override fun contentLength() = fileSystem.metadata(this@asRequestBody).size ?: -1
override fun writeTo(sink: BufferedSink) {
fileSystem.source(this@asRequestBody).use { source -> sink.writeAll(source) }
}
}
}
@JvmStatic
@Deprecated(
message = "Moved to extension function. Put the 'content' argument first to fix Java",
replaceWith =
ReplaceWith(
expression = "content.toRequestBody(contentType)",
imports = ["okhttp3.RequestBody.Companion.toRequestBody"],
),
level = DeprecationLevel.WARNING,
)
fun create(
contentType: MediaType?,
content: String,
): RequestBody = content.toRequestBody(contentType)
@JvmStatic
@Deprecated(
message = "Moved to extension function. Put the 'content' argument first to fix Java",
replaceWith =
ReplaceWith(
expression = "content.toRequestBody(contentType)",
imports = ["okhttp3.RequestBody.Companion.toRequestBody"],
),
level = DeprecationLevel.WARNING,
)
fun create(
contentType: MediaType?,
content: ByteString,
): RequestBody = content.toRequestBody(contentType)
@JvmOverloads
@JvmStatic
@Deprecated(
message = "Moved to extension function. Put the 'content' argument first to fix Java",
replaceWith =
ReplaceWith(
expression = "content.toRequestBody(contentType, offset, byteCount)",
imports = ["okhttp3.RequestBody.Companion.toRequestBody"],
),
level = DeprecationLevel.WARNING,
)
fun create(
contentType: MediaType?,
content: ByteArray,
offset: Int = 0,
byteCount: Int = content.size,
): RequestBody = content.toRequestBody(contentType, offset, byteCount)
@JvmStatic
@Deprecated(
message = "Moved to extension function. Put the 'file' argument first to fix Java",
replaceWith =
ReplaceWith(
expression = "file.asRequestBody(contentType)",
imports = ["okhttp3.RequestBody.Companion.asRequestBody"],
),
level = DeprecationLevel.WARNING,
)
fun create(
contentType: MediaType?,
file: File,
): RequestBody = file.asRequestBody(contentType)
/**
* Returns a gzip version of the RequestBody, with compressed payload.
* This is not automatic as not all servers support gzip compressed requests.
*
* ```
* val request = Request.Builder().url("...")
* .addHeader("Content-Encoding", "gzip")
* .post(uncompressedBody.gzip())
* .build()
* ```
*/
@JvmStatic
@ExperimentalOkHttpApi
fun RequestBody.gzip(): RequestBody {
return object : RequestBody() {
override fun contentType(): MediaType? {
return this@gzip.contentType()
}
override fun contentLength(): Long {
return -1 // We don't know the compressed length in advance!
}
@Throws(IOException::class)
override fun writeTo(sink: BufferedSink) {
GzipSink(sink).buffer().use(this@gzip::writeTo)
}
override fun isOneShot(): Boolean {
return this@gzip.isOneShot()
}
}
}
}
}