Passing arrays in multipart POST using Okhttp

穿精又带淫゛_ 提交于 2019-12-23 03:14:14

问题


I'm building an app that requires an API call that has array in its POST body request. I'm using OkHttp 2.6 to request for API.

The request in Postman looks like this:

I have tried several ways of writing RequestBody in order to achieve this,

  1. First method

    RequestBody requestBody = new MultipartBuilder()
            .type(MultipartBuilder.FORM)
            .addFormDataPart("app_token", MY_TOKEN)
            .addFormDataPart("user_id", 377)
            .addFormDataPart("group_id", String.valueOf(groupId))
            .addFormDataPart("key_id", deals.toString())
            .addFormDataPart("img", filename + ".jpg", fileBody)
            .build();
    
  2. Second method

    RequestBody requestBody = new MultipartBuilder()
            .type(MultipartBuilder.FORM)
            .addFormDataPart("app_token", MY_TOKEN)
            .addFormDataPart("user_id", 377)
            .addFormDataPart("group_id", String.valueOf(groupId))
            .addFormDataPart("key_id[0]", "33")
            .addFormDataPart("key_id[1]", "34")
            .addFormDataPart("img[0]", filename + ".jpg", fileBody)
            .build();
    
  3. Third method, which I found here.

    MediaType json = MediaType.parse("application/json; charset=utf-8");
    Map<String, Integer> params = new HashMap<>();
    for (int i = 0; i < deals.size(); i++) {
        params.put("key_id["+i+"]", Integer.valueOf(deals.get(i).getUid()));
    }
    JSONObject parameter = new JSONObject(params);
    RequestBody theBody = RequestBody.create(json, parameter.toString());
    
    
    RequestBody requestBodyyy = new MultipartBuilder()
            .type(MultipartBuilder.FORM)
            .addFormDataPart("app_token", MY_TOKEN)
            .addFormDataPart("user_id", 377)
            .addFormDataPart("group_id", String.valueOf(groupId))
            .addPart(theBody)
            .addFormDataPart("img[0]", filename + ".jpg", fileBody)
            .build();
    

But, none of them are working.

What is the correct way of doing this? I also need the array size to be dynamic as I'm not passing a static one.


回答1:


I am using Retrofit and Gson

private class AddImageAsyncTask extends AsyncTask<Void, Imageuploadpojo, Imageuploadpojo> {


        ApiCall a;
        String path1,path2;

        private AddImageAsyncTask(View vs, String path1,String path2) {
            this.vs = vs;
            this.path1 = path1;
             this.path2 = path2;         
            a = retrofit2.create(ApiCall.class);
        }



        @Override
        protected Imageuploadpojo doInBackground(Void... params) {
            Map<String, RequestBody> typedfile = new HashMap<String, RequestBody>();
            File f = new File(path1);
             File f2 = new File(path2);
            if (f.exists()) {
                RequestBody requestFile =
                        RequestBody.create(MediaType.parse("multipart/form-data"), f);
                String filename = f.getName();
                typedfile.put("fileToUpload" + "\"; filename=\"" + filename, requestFile);
                //   typedfile.put("img[0]" + count, requestFile);
            }
              if (f2.exists()) {
                RequestBody requestFile =
                        RequestBody.create(MediaType.parse("multipart/form-data"), f2);
                String filename = f.getName();
                typedfile.put("fileToUpload" + "\"; filename=\"" + filename, requestFile);
                //   typedfile.put("img[1]" + count, requestFile);
            }

            // asynchronous
            // Create a call instance for looking up Retrofit contributors.
            Call<Imageuploadpojo> call = a.ImageCall(typedfile);
            // Fetch and print a list of the contributors to the library.
            Imageuploadpojo c = null;
            try {
                c = call.execute().body();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return c;
        }

        @Override
        protected void onPostExecute(Imageuploadpojo c) {
            super.onPostExecute(c);

        }
    }

See this you can get idea. Or try it in retrofit

Code updated:

    //Create Hashmap:

         Map<String, RequestBody> typedfile = new HashMap<String, RequestBody>();

    //Add your file path

     File f2 = new File(path2);

    //Check the file is exist or not
     if (f2.exists()) {
    //Then Create RequestBody add file in second perameter
    RequestBody requestFile =
                            RequestBody.create(MediaType.parse("multipart/form-data"), f2);

      typedfile.put("img[1]" + "\"; filename=\"" + filename, requestFile);
//"img[1]" is parameter



回答2:


Heh, the solution seems easy. I've managed to solve this issue, so I'm gonna write here anyway for anyone seeking the same solution.

MultipartBuilder multipartBuilder = new MultipartBuilder()
        .type(MultipartBuilder.FORM)
        .addFormDataPart("token", MY_TOKEN)
        .addFormDataPart("user_id", user_id)
        .addFormDataPart("group_id", group_id)
        // .addFormDataPart("img[0]", filename + ".jpg", RequestBody.create(MediaType.parse("image/png"), file));

for (int i = 0; i < keys.size(); i++) {
    multipartBuilder.addFormDataPart("key_id[" + i + "]", keys.get(i));
}

for (int i = 0; i < files.size(); i++) {
    filename = Utils.getSimpleTimestamp();
    multipartBuilder.addFormDataPart("img[" + i + "]", filename + ".jpg", RequestBody.create(MediaType.parse("image/png"), files.get(i)));
}

RequestBody requestBody = multipartBuilder.build();
Request request = new Request.Builder()
        .url(API_URL)
        .post(requestBody)
        .addHeader("content-type", "multipart/form-data;")
        .build();

OkHttpClient okHttpClient = new OkHttpClient();


来源:https://stackoverflow.com/questions/38718439/passing-arrays-in-multipart-post-using-okhttp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!