小编典典

如何在OkHttpClient中将对象(即UserData)类型的列表添加到MultipartBody

json

我有一个对象的ArrayList我需要放入MultipartBody.Builder中。我尝试使用.addFormDataPart的不同方法,但无法正常工作。这就是我将其放入请求的方式。任何帮助,将不胜感激。谢谢

我在服务器上的JSON格式如下

 {
      "formData": [
        {
          "name": "string",
          "value": {
            any-object(string,file,long....etc)
          }
        }
      ],
      "tripId": "string"
    }

这就是我的做法

private RequestBody getMultipartData(Object postData) {
        MultipartBody.Builder formBody = new MultipartBody.Builder();
        formBody.setType(MultipartBody.FORM);

        ArrayList<UserData> arrayList = null;
        if (postData instanceof OnboardPresenterImpl.TripRequest) {
            OnboardPresenterImpl.TripRequest tripRequest = ((OnboardPresenterImpl.TripRequest) postData);
            formBody.addFormDataPart("tripId", tripRequest.getTripId());
            arrayList = tripRequest.getFormData();

        }

        if (arrayList != null && arrayList.size() > 0) {
            for (int i = 0; i < arrayList.size(); i++) {

                UserData userData = arrayList.get(i);

                String value = userData.getValue().toLowerCase();

                if (value.contains("/") && (value.contains(".png") ||
                        value.contains(".jpeg") || value.contains(".jpg"))) {

                    MediaType type = Util.getMediaType(value);

                    File sourceFile = new File(value);

                    if (sourceFile.exists()) {

                        formBody.addFormDataPart(userData.getName(),
                                sourceFile.getName(),RequestBody.create(type, sourceFile));

                    }
                } else {
                    formBody.addFormDataPart(userData.getName(), value);
                }
            }
        }

       return formBody.build();
    }

阅读 343

收藏
2020-07-27

共1个答案

小编典典

几天后,我想出了解决方案

String uploadMultipleFiles(Api api, HashMap<String, ArrayList<File>> fileListMap)
            throws IOException {

        String responseS;
        OkHttpClient timeOut = getOkHttpClient(api.getTimeOut());

        MultipartBody.Builder multipartBuilder = new MultipartBody.Builder()
                .setType(MultipartBody.FORM);
        int j = 0;
        ArrayList<File> fileList;
        for (Map.Entry<String, ArrayList<File>> entry : fileListMap.entrySet()) {
            String key = entry.getKey();
            fileList = entry.getValue();

            multipartBuilder.addFormDataPart("data[" + j + "].name", key);

            if (fileList != null) {
                for (int i = 0; i < fileList.size(); i++) {

                    File fileListRequest = fileList.get(i);

                    if (fileListRequest.exists()) {
                        String ext = CommonUtils.getExtension(fileListRequest.getName());
                        /* Changing Media Type whether JPEG or PNG **/
                        final MediaType MEDIA_TYPE = ext.endsWith("png") ? MEDIA_TYPE_PNG :
                                ext.endsWith("jpg") ? MEDIA_TYPE_JPG : MEDIA_TYPE_JPEG;

                        multipartBuilder.addFormDataPart("data[" + j + "].files[" + i + "]",
                                fileListRequest.getName(),
                                RequestBody.create(MEDIA_TYPE, fileListRequest));

                    }
                }
            }
            j++;
        }
        RequestBody requestBody = multipartBuilder.build();
        Request.Builder requestBuilder = new Request.Builder()
                .url(Objects.requireNonNull(api.getUrl()))
                .post(requestBody);
        buildHeaders(requestBuilder);
        Response response = timeOut.newCall(requestBuilder.build()).execute();
        responseS = response.body().string();
        Log.i(api.getName().name(), responseS);
        return responseS;
    }
2020-07-27