1
0
mirror of https://github.com/square/okhttp.git synced 2025-07-31 05:04:26 +03:00

Replace MediaType.get(string) with string.toMediaType() (#5132)

This commit is contained in:
Jesse Wilson
2019-05-27 01:38:35 -04:00
committed by Yuri Schimke
parent 568c6813b1
commit 53ba4dd9ef
12 changed files with 67 additions and 57 deletions

View File

@ -21,6 +21,7 @@ import com.github.rvesse.airline.annotations.Arguments
import com.github.rvesse.airline.annotations.Command
import com.github.rvesse.airline.annotations.Option
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.OkHttpClient
import okhttp3.Protocol
import okhttp3.Request
@ -214,7 +215,7 @@ class Main : Runnable {
return@let null
} ?: "application/x-www-form-urlencoded"
return MediaType.parse(mimeType)
return mimeType.toMediaTypeOrNull()
}
private fun close() {

View File

@ -21,6 +21,7 @@ import okhttp3.Callback
import okhttp3.Dns
import okhttp3.HttpUrl
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
import okhttp3.Protocol
import okhttp3.Request
@ -302,7 +303,7 @@ class DnsOverHttps internal constructor(builder: Builder) : Dns {
}
companion object {
val DNS_MESSAGE: MediaType = MediaType.get("application/dns-message")
val DNS_MESSAGE: MediaType = "application/dns-message".toMediaType()
const val MAX_RESPONSE_SIZE = 64 * 1024
private fun buildBootstrapClient(builder: Builder): Dns {

View File

@ -15,6 +15,7 @@
*/
package okhttp3.internal.sse
import okhttp3.internal.toLongOrDefault
import okio.Buffer
import okio.BufferedSource
import okio.ByteString.Companion.encodeUtf8
@ -151,11 +152,7 @@ class ServerSentEventReader(
@Throws(IOException::class)
private fun BufferedSource.readRetryMs(): Long {
val retryString = readUtf8LineStrict()
return try {
retryString.toLong()
} catch (_: NumberFormatException) {
-1L
}
return retryString.toLongOrDefault(-1L)
}
}
}

View File

@ -15,6 +15,7 @@
*/
package okhttp3
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.internal.EMPTY_HEADERS
import okhttp3.internal.cache.CacheRequest
import okhttp3.internal.cache.CacheStrategy
@ -24,6 +25,7 @@ import okhttp3.internal.http.HttpMethod
import okhttp3.internal.http.StatusLine
import okhttp3.internal.io.FileSystem
import okhttp3.internal.platform.Platform
import okhttp3.internal.toLongOrDefault
import okio.Buffer
import okio.BufferedSink
import okio.BufferedSource
@ -676,17 +678,9 @@ class Cache internal constructor(
}.buffer()
}
override fun contentType(): MediaType? {
return if (contentType != null) MediaType.parse(contentType) else null
}
override fun contentType(): MediaType? = contentType?.toMediaTypeOrNull()
override fun contentLength(): Long {
return try {
contentLength?.toLong() ?: -1
} catch (_: NumberFormatException) {
-1L
}
}
override fun contentLength(): Long = contentLength?.toLongOrDefault(-1L) ?: -1L
override fun source(): BufferedSource = bodySource
}

View File

@ -16,13 +16,13 @@
package okhttp3
import okhttp3.internal.UTC
import okhttp3.internal.delimiterOffset
import okhttp3.internal.indexOfControlOrNonAscii
import okhttp3.internal.trimSubstring
import okhttp3.internal.http.HttpDate
import okhttp3.internal.canParseAsIpAddress
import okhttp3.internal.delimiterOffset
import okhttp3.internal.http.HttpDate
import okhttp3.internal.indexOfControlOrNonAscii
import okhttp3.internal.publicsuffix.PublicSuffixDatabase
import okhttp3.internal.toCanonicalHost
import okhttp3.internal.trimSubstring
import java.util.Calendar
import java.util.Collections
import java.util.Date
@ -532,11 +532,10 @@ data class Cookie private constructor(
}
/**
* Returns the positive value if `attributeValue` is positive, or [Long.MIN_VALUE] if it is
* either 0 or negative. If the value is positive but out of range, this returns
* [Long.MAX_VALUE].
* Returns the positive value if [s] is positive, or [Long.MIN_VALUE] if it is either 0 or
* negative. If the value is positive but out of range, this returns [Long.MAX_VALUE].
*
* @throws NumberFormatException if `s` is not an integer of any precision.
* @throws NumberFormatException if [s] is not an integer of any precision.
*/
private fun parseMaxAge(s: String): Long {
try {

View File

@ -18,6 +18,7 @@ package okhttp3
import okhttp3.HttpUrl.Companion.FORM_ENCODE_SET
import okhttp3.HttpUrl.Companion.canonicalize
import okhttp3.HttpUrl.Companion.percentDecode
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.internal.toImmutableList
import okio.Buffer
import okio.BufferedSink
@ -120,6 +121,6 @@ class FormBody internal constructor(
}
companion object {
private val CONTENT_TYPE: MediaType = MediaType.get("application/x-www-form-urlencoded")
private val CONTENT_TYPE: MediaType = "application/x-www-form-urlencoded".toMediaType()
}
}

View File

@ -85,24 +85,25 @@ class MediaType private constructor(
private val PARAMETER = Pattern.compile(";\\s*(?:$TOKEN=(?:$TOKEN|$QUOTED))?")
/**
* Returns a media type for [string].
* Returns a media type for this string.
*
* @throws IllegalArgumentException if [string] is not a well-formed media type.
* @throws IllegalArgumentException if this is not a well-formed media type.
*/
@JvmStatic
fun get(string: String): MediaType {
val typeSubtype = TYPE_SUBTYPE.matcher(string)
require(typeSubtype.lookingAt()) { "No subtype found for: \"$string\"" }
@JvmName("get")
fun String.toMediaType(): MediaType {
val typeSubtype = TYPE_SUBTYPE.matcher(this)
require(typeSubtype.lookingAt()) { "No subtype found for: \"$this\"" }
val type = typeSubtype.group(1).toLowerCase(Locale.US)
val subtype = typeSubtype.group(2).toLowerCase(Locale.US)
var charset: String? = null
val parameter = PARAMETER.matcher(string)
val parameter = PARAMETER.matcher(this)
var s = typeSubtype.end()
while (s < string.length) {
parameter.region(s, string.length)
while (s < length) {
parameter.region(s, length)
require(parameter.lookingAt()) {
"Parameter is not formatted correctly: \"${string.substring(s)}\" for: \"$string\""
"Parameter is not formatted correctly: \"${substring(s)}\" for: \"$this\""
}
val name = parameter.group(1)
@ -124,23 +125,42 @@ class MediaType private constructor(
else -> token
}
require(charset == null || charsetParameter.equals(charset, ignoreCase = true)) {
"Multiple charsets defined: \"$charset\" and: \"$charsetParameter\" for: \"$string\""
"Multiple charsets defined: \"$charset\" and: \"$charsetParameter\" for: \"$this\""
}
charset = charsetParameter
s = parameter.end()
}
return MediaType(string, type, subtype, charset)
return MediaType(this, type, subtype, charset)
}
/** Returns a media type for [string], or null if [string] is not a well-formed media type. */
/** Returns a media type for this, or null if this is not a well-formed media type. */
@JvmStatic
fun parse(string: String): MediaType? {
@JvmName("parse")
fun String.toMediaTypeOrNull(): MediaType? {
return try {
get(string)
toMediaType()
} catch (_: IllegalArgumentException) {
null
}
}
@JvmName("-deprecated_get")
@Deprecated(
message = "moved to extension function",
replaceWith = ReplaceWith(
expression = "mediaType.toMediaType()",
imports = ["okhttp3.MediaType.Companion.toMediaType"]),
level = DeprecationLevel.WARNING)
fun get(mediaType: String): MediaType = mediaType.toMediaType()
@JvmName("-deprecated_parse")
@Deprecated(
message = "moved to extension function",
replaceWith = ReplaceWith(
expression = "mediaType.toMediaTypeOrNull()",
imports = ["okhttp3.MediaType.Companion.toMediaTypeOrNull"]),
level = DeprecationLevel.WARNING)
fun parse(mediaType: String): MediaType? = mediaType.toMediaTypeOrNull()
}
}

View File

@ -15,7 +15,7 @@
*/
package okhttp3
import okhttp3.RequestBody.Companion.toRequestBody
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.internal.toImmutableList
import okio.Buffer
import okio.BufferedSink
@ -34,7 +34,7 @@ class MultipartBody internal constructor(
@get:JvmName("type") val type: MediaType,
@get:JvmName("parts") val parts: List<Part>
) : RequestBody() {
private val contentType: MediaType = MediaType.get("$type; boundary=$boundary")
private val contentType: MediaType = "$type; boundary=$boundary".toMediaType()
private var contentLength = -1L
@get:JvmName("boundary") val boundary: String
@ -280,7 +280,7 @@ class MultipartBody internal constructor(
* does not recognize must be treated as being of subtype "mixed".
*/
@JvmField
val MIXED = MediaType.get("multipart/mixed")
val MIXED = "multipart/mixed".toMediaType()
/**
* The "multipart/alternative" type is syntactically identical to "multipart/mixed", but the
@ -288,7 +288,7 @@ class MultipartBody internal constructor(
* the same information.
*/
@JvmField
val ALTERNATIVE = MediaType.get("multipart/alternative")
val ALTERNATIVE = "multipart/alternative".toMediaType()
/**
* This type is syntactically identical to "multipart/mixed", but the semantics are different.
@ -296,14 +296,14 @@ class MultipartBody internal constructor(
* "text/plain" to "message/rfc822".
*/
@JvmField
val DIGEST = MediaType.get("multipart/digest")
val DIGEST = "multipart/digest".toMediaType()
/**
* This type is syntactically identical to "multipart/mixed", but the semantics are different.
* In particular, in a parallel entity, the order of body parts is not significant.
*/
@JvmField
val PARALLEL = MediaType.get("multipart/parallel")
val PARALLEL = "multipart/parallel".toMediaType()
/**
* The media-type multipart/form-data follows the rules of all multipart MIME data streams as
@ -311,7 +311,7 @@ class MultipartBody internal constructor(
* fills out the form. Each field has a name. Within a given form, the names are unique.
*/
@JvmField
val FORM = MediaType.get("multipart/form-data")
val FORM = "multipart/form-data".toMediaType()
private val COLONSPACE = byteArrayOf(':'.toByte(), ' '.toByte())
private val CRLF = byteArrayOf('\r'.toByte(), '\n'.toByte())

View File

@ -15,6 +15,7 @@
*/
package okhttp3
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.internal.checkOffsetAndCount
import okio.BufferedSink
import okio.ByteString
@ -103,7 +104,7 @@ abstract class RequestBody {
val resolvedCharset = contentType.charset()
if (resolvedCharset == null) {
charset = UTF_8
finalContentType = MediaType.parse("$contentType; charset=utf-8")
finalContentType = "$contentType; charset=utf-8".toMediaTypeOrNull()
} else {
charset = resolvedCharset
}

View File

@ -15,6 +15,7 @@
*/
package okhttp3
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.internal.closeQuietly
import okhttp3.internal.readBomAsCharset
import okio.Buffer
@ -216,7 +217,7 @@ abstract class ResponseBody : Closeable {
val resolvedCharset = contentType.charset()
if (resolvedCharset == null) {
charset = UTF_8
finalContentType = MediaType.parse("$contentType; charset=utf-8")
finalContentType = "$contentType; charset=utf-8".toMediaTypeOrNull()
} else {
charset = resolvedCharset
}

View File

@ -16,6 +16,7 @@
package okhttp3.internal.http
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.ResponseBody
import okio.BufferedSource
@ -31,13 +32,7 @@ class RealResponseBody(
override fun contentLength(): Long = contentLength
override fun contentType(): MediaType? {
return if (contentTypeString != null) {
MediaType.parse(contentTypeString)
} else {
null
}
}
override fun contentType(): MediaType? = contentTypeString?.toMediaTypeOrNull()
override fun source(): BufferedSource = source
}

View File

@ -129,7 +129,7 @@ class Jdk8WithJettyBootPlatform(
// 1.8, 9, 10, 11, 12 etc
val version = jvmVersion.toInt()
if (version >= 9) return null
} catch (nfe: NumberFormatException) {
} catch (_: NumberFormatException) {
// expected on >= JDK 9
}