Square's meticulous HTTP client for Java and Kotlin
—
Form data and multipart request body construction for file uploads and form submissions.
For application/x-www-form-urlencoded requests.
class FormBody private constructor() : RequestBody() {
val size: Int
fun encodedName(index: Int): String
fun name(index: Int): String
fun encodedValue(index: Int): String
fun value(index: Int): String
class Builder {
fun add(name: String, value: String): Builder
fun addEncoded(name: String, value: String): Builder
fun build(): FormBody
}
}For multipart/form-data requests, typically used for file uploads.
class MultipartBody private constructor() : RequestBody() {
val type: MediaType
val boundary: String
val size: Int
fun part(index: Int): Part
fun parts(): List<Part>
class Builder {
constructor()
constructor(boundary: String)
fun setType(type: MediaType): Builder
fun addPart(body: RequestBody): Builder
fun addPart(headers: Headers?, body: RequestBody): Builder
fun addFormDataPart(name: String, value: String): Builder
fun addFormDataPart(name: String, filename: String?, body: RequestBody): Builder
fun build(): MultipartBody
}
class Part private constructor() {
val headers: Headers?
val body: RequestBody
companion object {
fun create(body: RequestBody): Part
fun create(headers: Headers?, body: RequestBody): Part
fun createFormData(name: String, value: String): Part
fun createFormData(name: String, filename: String?, body: RequestBody): Part
}
}
companion object {
val MIXED: MediaType
val ALTERNATIVE: MediaType
val DIGEST: MediaType
val PARALLEL: MediaType
val FORM: MediaType
}
}val file = File("photo.jpg")
val requestBody = file.asRequestBody("image/jpeg".toMediaType())
val multipartBody = MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("title", "My Photo")
.addFormDataPart("photo", "photo.jpg", requestBody)
.build()
val request = Request.Builder()
.url("https://api.example.com/upload")
.post(multipartBody)
.build()Install with Tessl CLI
npx tessl i tessl/maven-com-squareup-okhttp3--okhttp