使用Okhttp在多部分POST中传递数组 [英] Passing arrays in multipart POST using Okhttp

查看:1478
本文介绍了使用Okhttp在多部分POST中传递数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个需要POST正文请求中包含数组的API调用的应用程序.我正在使用OkHttp 2.6请求API.

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:

为了达到这个目的,我尝试了几种编写RequestBody的方法,

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

  1. 第一种方法

  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();

  • 第二种方法

  • 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();
    

  • 第三种方法,我发现了这里.

    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.

    推荐答案

    我正在使用Retrofit和Gson

    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

    代码已更新:

        //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
    

    这篇关于使用Okhttp在多部分POST中传递数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆