RequestBodyUtil.kt 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. package io.github.zadam.triliumsender.services
  2. import okhttp3.MediaType
  3. import okhttp3.RequestBody
  4. import okhttp3.internal.Util
  5. import okio.BufferedSink
  6. import okio.Okio
  7. import okio.Source
  8. import java.io.IOException
  9. import java.io.InputStream
  10. object RequestBodyUtil {
  11. fun create(mediaType: MediaType, inputStream: InputStream): RequestBody {
  12. return object : RequestBody() {
  13. override fun contentType(): MediaType? {
  14. return mediaType
  15. }
  16. override fun contentLength(): Long {
  17. try {
  18. return inputStream.available().toLong()
  19. } catch (e: IOException) {
  20. return 0
  21. }
  22. }
  23. @Throws(IOException::class)
  24. override fun writeTo(sink: BufferedSink) {
  25. var source: Source? = null
  26. try {
  27. source = Okio.source(inputStream)
  28. sink.writeAll(source!!)
  29. } finally {
  30. Util.closeQuietly(source)
  31. }
  32. }
  33. }
  34. }
  35. }