StreamHelper.kt 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. // тут должен быть ван package
  2. import okhttp3.MediaType
  3. import okhttp3.RequestBody
  4. import okhttp3.internal.closeQuietly
  5. import okio.BufferedSink
  6. import okio.Source
  7. import okio.source
  8. import java.io.*
  9. /**
  10. * Created by yuanxin on 1/30/2018.
  11. */
  12. object StreamHelper {
  13. fun create(mediaType: MediaType?, inputStream: InputStream): RequestBody {
  14. return object : RequestBody() {
  15. override fun contentType(): MediaType? {
  16. return mediaType
  17. }
  18. override fun contentLength(): Long {
  19. return try {
  20. inputStream.available().toLong()
  21. } catch (e: IOException) {
  22. 0
  23. }
  24. }
  25. @Throws(IOException::class)
  26. override fun writeTo(sink: BufferedSink) {
  27. var source: Source? = null
  28. try {
  29. source = inputStream.source()
  30. sink.writeAll(source)
  31. } finally {
  32. source!!.closeQuietly()
  33. }
  34. }
  35. }
  36. }
  37. }