StreamHelper.kt 1.2 KB

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