Skip to content

Instantly share code, notes, and snippets.

@gbzarelli
Last active May 25, 2022 09:05
Show Gist options
  • Save gbzarelli/a7ac6d487e9c2cf3885c5b6c56cc6996 to your computer and use it in GitHub Desktop.
Save gbzarelli/a7ac6d487e9c2cf3885c5b6c56cc6996 to your computer and use it in GitHub Desktop.
OkHttp RequestBody based in InputStream
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);
}
}
}
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