android - Creating a proper MultipartBuilder Http Request with OKHttp -



android - Creating a proper MultipartBuilder Http Request with OKHttp -

ild recode project , utilize okhttp instead of default httpclient implemented in android.

i've downloaded latest source of okhttp-main release.

now ive found examples how create , build post request.

now problem. want create requestbody maintain several info (strings, files, whatever) can't assign them directly.

means requestbuilder must go through different loops it's info added.

okhttps requestbody seems need info immediatly listed in illustration https://github.com/square/okhttp/wiki/recipes

when want seek like

requestbody requestbody = new multipartbuilder().type(multipartbuilder.form); (object amdata : dataclass.getdata().entryset()) { map.entry mapentry = (map.entry) amdata; string keyvalue = (string) mapentry.getkey(); string value = (string) mapentry.getvalue(); requestbody.addpart(keyvalue, value); } (datapackage datapackage : dataclass.getdatapackages()) { requestbody.addpart("upfile[]", datapackage.getfile()); } requestbody.build();

it fails because build() create requestbody. before it's multipartbuilder(). if seek forcefulness type requestbody wont compile/run.

so, proper way adding thos info after creating multipartbuilder , add together info , strings?

uploading file in multipart using okhttp

private static final string imgur_client_id = "..."; private static final mediatype media_type_png = mediatype.parse("image/png"); private final okhttpclient client = new okhttpclient(); public void run() throws exception { // utilize imgur image upload api documented @ https://api.imgur.com/endpoints/image requestbody requestbody = new multipartbuilder() .type(multipartbuilder.form) .addpart( headers.of("content-disposition", "form-data; name=\"title\""), requestbody.create(null, "square logo")) .addpart( headers.of("content-disposition", "form-data; name=\"image\""), requestbody.create(media_type_png, new file("website/static/logo-square.png"))) .build(); request request = new request.builder() .header("authorization", "client-id " + imgur_client_id) .url("https://api.imgur.com/3/image") .post(requestbody) .build(); response response = client.newcall(request).execute(); if (!response.issuccessful()) throw new ioexception("unexpected code " + response); system.out.println(response.body().string()); }

android multipartform-data okhttp

Comments

Popular posts from this blog

model view controller - MVC Rails Planning -

ruby on rails - Devise Logout Error in RoR -

html - Submenu setup with jquery and effect 'fold' -