Search code examples
androidretrofit2multipart

How to send List of integers along with image in retrofit2 using Multipart


I am trying to upload an image using retrofit 2.0., I have few other params to be send with form data which include a List of integers. My request declaration is

@Multipart
@POST("/api/Add")
    Call<AddResponse> addApi(@Part("Id") RequestBody id,
                             @Part("Name") RequestBody name,
                             @Part("Description") RequestBody description,
                             @Part("Phone") RequestBody phone,
                             @Part MultipartBody.Part logo,
                             @Part("WorkingDays") RequestBody workingDays,
                             @Part("CitiesIDs") RequestBody cities);
public class RetrofitService {

    private static Retrofit retrofit;
    private static final Object LOCK = new Object();
    private static final String BASE_URL = "https://baseurl.app";

    public static Retrofit getRetrofitInstance() {

        OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
        httpClient.addInterceptor(chain -> {
            Request original = chain.request();

            Request.Builder requestBuilder = original.newBuilder()
           .addHeader("Content-Type", "application/json");

            Request request = requestBuilder.build();
            return chain.proceed(request);
        });

        OkHttpClient client = httpClient.build();

        HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
        logging.setLevel(HttpLoggingInterceptor.Level.BODY);
        httpClient.addInterceptor(logging);
        httpClient.readTimeout(60, TimeUnit.SECONDS);
        httpClient.connectTimeout(60, TimeUnit.SECONDS);
        if (retrofit == null) {
            synchronized (LOCK) {
                retrofit = new retrofit2.Retrofit.Builder()
                        .baseUrl(BASE_URL)
                        .client(client)
                        .addConverterFactory(ScalarsConverterFactory.create())
                        .addConverterFactory(GsonConverterFactory.create())
                        .client(httpClient.build())
                        .build();
            }
        }

        return retrofit;
    }

This way not working as expectedو the list of integers sent separately like below.

Content-Disposition: form-data; name="CitiesIDs"
Content-Transfer-Encoding: binary
Content-Type: multipart/form-data; boundary=290d2964-526a-48b9-b742-c6a3b547c7d6
Content-Length: 286
--290d2964-526a-48b9-b742-c6a3b547c7d6
Content-Disposition: form-data; name="CitiesIDs"
Content-Length: 1
7
--290d2964-526a-48b9-b742-c6a3b547c7d6
Content-Disposition: form-data; name="CitiesIDs"
Content-Length: 1
8
--290d2964-526a-48b9-b742-c6a3b547c7d6--

Also, to convert list of integers to RequestBody i used below way

okhttp3.MultipartBody.Builder citiesRequestBodyBuilder = new MultipartBody.Builder().setType(MultipartBody.FORM);

  for(int i=0; i<citiesIdList.size(); ++i){
  citiesRequestBodyBuilder.addFormDataPart("CitiesIDs", String.valueOf(citiesIdList.get(i)));
   }

Since Add a form data part method addFormDataPart accept strings only so i had to convert integers to string which make server respond with the below message

 {"Success":false,
  "ErrorMessage":"Input string '--290d2964-526a-48b9-b742-c6a3b547c7d6' is not a valid number. Path '', line 1, position 38.",
 "Id":0}

Postman, works fine enter image description here So how can i send image and list of integers using Multipart.

The problem is RequestBody only accepts File, byte[], String, ByteString How can I send List of integers With @part.

Thanks for your help.


Solution

  • you have to use MultipartBody.Part only for file and other field should with RequestBody.

    Remove your below code

    for(int i=0; i<citiesIdList.size(); ++i){
      citiesRequestBodyBuilder.addFormDataPart("CitiesIDs", String.valueOf(citiesIdList.get(i)));
       }
    

    Use

     // Add other field here
    RequestBody description =
                RequestBody.create(
                        okhttp3.MultipartBody.FORM, Gson().toJson(citiesIdList));