I'm developing an application where at a point the user has to choose any number of countries from a list and I must send the selected names through a multipart.
I am not uploading any file along with the String[], but there is no route to upload information without it being a multipart and I don't have any saying in how the web server operates.
I've attempted to simply send it as an Array, ArrayList and JsonArray as such:
@Headers({
"Connection: Keep-Alive",
})
@Multipart
@PUT("/user/{id}")
String updateUser(@Path("id") int userId, @Part("user[countries]") String[] countries);
I've also attempted this solution, but I either misunderstood it or it does not work. Here is the code I attempted to use:
ArrayList<String> countries = CountryManager.getInstance().getSelectedCountryIds();
RequestBody requestBody;
LinkedHashMap<String, RequestBody> hashMap = new LinkedHashMap<>();
for(int i = 0; i < countries.size(); i++) {
requestBody = RequestBody.create(MediaType.parse("text/plain"), countries.get(i));
hashMap.put("countries["+i+"]", requestBody);
}
And changing the retrofit method accordingly:
@Headers({
"Connection: Keep-Alive",
})
@Multipart
@PUT("/user/{id}")
String updateUser(@Path("id") int userId, @PartMap() Map countries);
However in all attempts I've gotten the error retrofit.RetrofitError: Part body must not be null.
I've also mentioned that the ChangeLog for retrofit mentions "New: Support iterable and array @Part
parameters using OkHttp's MultipartBody.Part
", but after some digging, I've found the given example quite confusing to the point that I'm unsure on how to implement it in my code and was unable to find a tutorial that even mentioned sending arrays in a multipart.
Is such a thing simply impossible?
Prepare the Retrofit Interface We annotate the call method @Multipart to denote the Request Body. Doing this we can now submit our data in the parameters as @PartMap and @Part . @PartMap will contain our map data prepared for the textual data and the rating list.
creating multi part list to use as a array list
List<MultipartBody.Part> descriptionList = new ArrayList<>();
descriptionList.add(MultipartBody.Part.createFormData("param_name_here", values));
following is the function in service interface of retrofit.
@PUT("/")
@Multipart
Call<ResponseBody> uploadPhotos(
@Part MultipartBody.Part placeId,
@Part MultipartBody.Part name,
@Part List<MultipartBody.Part> desclist, // <-- use such for list of same parameter
@Part List<MultipartBody.Part> files // <-- multiple photos here
);
Hope it helps someone. cheers... !!!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With