How to Post image and data in android retrofit

2019-08-17 02:28发布

问题:

I am unable to post data and image using retrofit. can u please help me

@Multipart
@POST("click_and_post")
Call<ResponseBody> clicPost(
    @Part ("click_and_post[image]") RequestBody file,
    @Part ("click_and_post[category_id]") String  category_id,
    @Part ("click_and_post[brand_id]") String  brand_id,
    @Part ("click_and_post[location]") String  location);

POst man I am unable to send data can u help me

回答1:

This is how you should implement this api

    int size = youImagePathList.size();

    MultipartBody.Part[] multipartImageList = new MultipartBody.Part[size];

    if(size > 0) {

        for (int i = 0; i < size; i++) {
            File file = new File(notificationItemList.get(i).getImageEncoded());
            RequestBody surveyBody = RequestBody.create(MediaType.parse("image/*"), file);
            multipartImageList[i] = MultipartBody.Part.createFormData(""click_and_post[image]"", file.getName(), surveyBody);
        }

    }



RequestBody category_id = RequestBody.create(MediaType.parse("multipart/form-data"), StringCategoryID);
RequestBody brand_id = RequestBody.create(MediaType.parse("multipart/form-data"), StringBrandId);
RequestBody location = RequestBody.create(MediaType.parse("multipart/form-data"), StringLocation);

    @Multipart
    @POST("click_and_post")
    Call<ResponseBody> clicPost(
                @Header("Authorization") String authorization,  // if there is headers
                @Part  MultipartBody.Part[] multipartImageList,
                @Part("click_and_post[category_id]") RequestBody category_id,
                @Part("click_and_post[brand_id]") RequestBody brand_id,
                @Part("click_and_post[location]") RequestBody location);