Akbar Begimqulov Akbar Begimqulov - 2 months ago 37
Android Question

multipart file upload by okhttp in android

Generated the code below by postman:

OkHttpClient client = new OkHttpClient();

MediaType mediaType = MediaType.parse("multipart/form-data; boundary=---011000010111000001101001");
RequestBody body = RequestBody.create(mediaType, "-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"image\"; filename=\"[object Object]\"\r\nContent-Type: false\r\n\r\n\r\n-----011000010111000001101001--");
Request request = new Request.Builder()
.url("http://foobar.com/newsfeed/photo")
.post(body)
.addHeader("content-type", "multipart/form-data; boundary=---011000010111000001101001")
.addHeader("x-access-token", "MczCvMEbllNhGaMwEDnGXuQjrwBAYuYleFlgsUZDWRYbVaohpEGgofonYcvHsgPaTnbzHxCvJWalYFTY")
.addHeader("accept-language", "ru")
.build();

Response response = client.newCall(request).execute();


This request make a file on Server with 0 Kb size. and I couldn't put a file. So, I have to put a file like this:

RequestBody body = RequestBody.create(mediaType, new File(filename));


But I got TimeOutExaption.

How to put a file by this kind of Rest API?

Answer

I found a way to multipart file upload by Ion.

Ion.with(context).load(url).setHeader("x-access-token", token)
            .setMultipartParameter("x-access-token", token)
            .setMultipartContentType("multipart/form-data")
            .setMultipartFile("image", "image/jpeg", file)
            .asString().withResponse().setCallback(new FutureCallback<Response<String>>() {
        @Override
        public void onCompleted(Exception e, Response<String> result) {
            if (result != null)
                onSuccess(result.getResult(), result.getHeaders().code());
        }
    });

Rest API: enter image description here

enter image description here