Last active
May 25, 2022 09:05
-
-
Save gbzarelli/a7ac6d487e9c2cf3885c5b6c56cc6996 to your computer and use it in GitHub Desktop.
OkHttp RequestBody based in InputStream
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class InputStreamRequestBody extends RequestBody { | |
private final InputStream inputStream; | |
private final MediaType contentType; | |
public InputStreamRequestBody(MediaType contentType, InputStream inputStream) { | |
if (inputStream == null) throw new NullPointerException("inputStream == null"); | |
this.contentType = contentType; | |
this.inputStream = inputStream; | |
} | |
@Nullable | |
@Override | |
public MediaType contentType() { | |
return contentType; | |
} | |
@Override | |
public long contentLength() throws IOException { | |
return inputStream.available() == 0 ? -1 : inputStream.available(); | |
} | |
@Override | |
public void writeTo(@NonNull BufferedSink sink) throws IOException { | |
Source source = null; | |
try { | |
source = Okio.source(inputStream); | |
sink.writeAll(source); | |
} finally { | |
Util.closeQuietly(source); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class UriRequestBody extends RequestBody { | |
private final MediaType contentType; | |
private final ContentResolver contentResolver; | |
private final Uri uri; | |
public UriRequestBody(MediaType contentType, ContentResolver contentResolver, Uri uri) { | |
if (uri == null) throw new NullPointerException("uri == null"); | |
this.contentType = contentType; | |
this.contentResolver = contentResolver; | |
this.uri = uri; | |
} | |
@Nullable | |
@Override | |
public MediaType contentType() { | |
return contentType; | |
} | |
@Override | |
public long contentLength() throws IOException { | |
return -1; | |
} | |
@Override | |
public void writeTo(@NonNull BufferedSink sink) throws IOException { | |
Source source = null; | |
try { | |
source = Okio.source(contentResolver.openInputStream(uri)); | |
sink.writeAll(source); | |
} finally { | |
Util.closeQuietly(source); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment