okhttp icon indicating copy to clipboard operation
okhttp copied to clipboard

Creating RequestBody from an InputStream

Open jianghaolu opened this issue 10 years ago • 9 comments

I was looking at RequestBody.java and I can't find an overload for create() like this:

RequestBody.create(MediaType contentType, InputStream stream)'

Is there a reason not to implement this? This is pretty useful when piping from one stream into an upload job. The overload accepting a File is useful for files but that's not the only scenario where buffering in memory does not work.

Please shed some lights if I'm missing something. Thanks!

jianghaolu avatar Mar 21 '16 22:03 jianghaolu

In general we want to be able to replay a request body multiple times. But input streams can only be consumed once.

swankjesse avatar Mar 21 '16 23:03 swankjesse

So if I provide a large file it ~~will~~ might be read multiple times?

jianghaolu avatar Mar 21 '16 23:03 jianghaolu

Yep. For example, if you get a 308 redirect.

swankjesse avatar Mar 21 '16 23:03 swankjesse

Or retries. Makes sense! Thanks.

jianghaolu avatar Mar 22 '16 21:03 jianghaolu

Course of project , i need the overload , do you find answers?

Ulanxx avatar Jan 17 '17 08:01 Ulanxx

Handling files on Android is not nice at all, so we need to use content:// URIs. We can get a streams from them, or File Descriptors, but not a file.

bpappin avatar Jul 30 '18 21:07 bpappin

The Uri is what you should create a RequestBody from then. As if it needs to be written twice it can have its stream opened twice.

JakeWharton avatar Jul 30 '18 21:07 JakeWharton

@JakeWharton yes i agree, but there is no RequestBody.create(MimeType, Uri) that i can see.

The only way I can see to do it is to override RequestBody and source from the file descriptor.

bpappin avatar Jul 30 '18 21:07 bpappin

Yep. That's the right way.

On Mon, Jul 30, 2018 at 5:38 PM Brill Pappin [email protected] wrote:

@JakeWharton https://github.com/JakeWharton yes i agree, but there is no RequestBody.create(MimeType, Uri) that i can see.

The only way I can see to do it is to override RequetBody and source from the file descriptor.

— You are receiving this because you were mentioned.

Reply to this email directly, view it on GitHub https://github.com/square/okhttp/issues/2424#issuecomment-409020429, or mute the thread https://github.com/notifications/unsubscribe-auth/AAEEEfH84q_iL-uf7-M4WMfOzMGEROUuks5uL3zkgaJpZM4H1nhR .

JakeWharton avatar Jul 30 '18 21:07 JakeWharton