android - Upload binary file with okhttp from resources -
i need upload binary file bundled in apk server using okhttp. using urlconnection, can inputstream asset , put request. however, okhttp gives option of uploading byte arrays, strings, or files. since can't file path asset bundled in apk, option copy file local file directory (i'd rather not that) , give file okhttp? there no way make request using assetinputstream directly web server?
edit: used accepted answer instead of making static utility class subclassed requestbody
public class inputstreamrequestbody extends requestbody { private inputstream inputstream; private mediatype mediatype; public static requestbody create(final mediatype mediatype, final inputstream inputstream) { return new inputstreamrequestbody(inputstream, mediatype); } private inputstreamrequestbody(inputstream inputstream, mediatype mediatype) { this.inputstream = inputstream; this.mediatype = mediatype; } @override public mediatype contenttype() { return mediatype; } @override public long contentlength() { try { return inputstream.available(); } catch (ioexception e) { return 0; } } @override public void writeto(bufferedsink sink) throws ioexception { source source = null; try { source = okio.source(inputstream); sink.writeall(source); } { util.closequietly(source); } } }
my concern approach unreliability of inputstream.available() content-length. static constructor match okhttp's internal implementation
you might not able directly using library create little utility class you. re-use everywhere need it.
public class requestbodyutil { public static requestbody create(final mediatype mediatype, final inputstream inputstream) { return new requestbody() { @override public mediatype contenttype() { return mediatype; } @override public long contentlength() { try { return inputstream.available(); } catch (ioexception e) { return 0; } } @override public void writeto(bufferedsink sink) throws ioexception { source source = null; try { source = okio.source(inputstream); sink.writeall(source); } { util.closequietly(source); } } }; } }
then use so
okhttpclient client = new okhttpclient(); mediatype media_type_markdown = mediatype.parse("text/x-markdown; charset=utf-8"); inputstream inputstream = getassets().open("readme.md"); requestbody requestbody = requestbodyutil.create(media_type_markdown, inputstream); request request = new request.builder() .url("https://api.github.com/markdown/raw") .post(requestbody) .build(); response response = client.newcall(request).execute(); if (!response.issuccessful()) throw new ioexception("unexpected code " + response); log.d("post", response.body().string());
this example code based on this code. replace assets
file name , mediatype
own.
Comments
Post a Comment