为了账号安全,请及时绑定邮箱和手机立即绑定

在 Retrofit 中将表单数据发送到服务器

在 Retrofit 中将表单数据发送到服务器

呼啦一阵风 2023-03-31 17:20:32
尝试通过 Retrofit 向服务器发送表单数据,但无法向服务器请求。我想用他们的数据发布一个图像数组。val builder: MultipartBody.Builder = MultipartBody.Builder().setType(MultipartBody.FORM);builder.addFormDataPart("device_id",device_UDID)builder.addFormDataPart("device_token",device_token)builder.addFormDataPart("device_type","android")builder.addFormDataPart("country_code",Constant.COUNTRY_CODE)builder.addFormDataPart("email",signUpBean.email)builder.addFormDataPart("mobile",signUpBean.phoneNumber)builder.addFormDataPart("first_name",signUpBean.firstName)builder.addFormDataPart("last_name",signUpBean.lastName)builder.addFormDataPart("gender",signUpBean.gender)builder.addFormDataPart("dob",signUpBean.dob)builder.addFormDataPart("city",signUpBean.city)builder.addFormDataPart("bike_type_id","1")builder.addFormDataPart("bike_model",signUpBean.mfg)builder.addFormDataPart("bike_manufacturer",signUpBean.mfg)builder.addFormDataPart("reg_year",signUpBean.mfgYear)builder.addFormDataPart("liecense_plate",signUpBean.licencePlateNo)builder.addFormDataPart("bank_ac_name",signUpBean.bnkHolderName)builder.addFormDataPart("bank_ac_number",signUpBean.bnkAccountNumber)builder.addFormDataPart("bank_name",signUpBean.bnkName)builder.addFormDataPart("bank_ifsc_code",signUpBean.ifscCode)builder.addFormDataPart(    "profile_pic",    "profile" + ".jpg",    RequestBody.create(MediaType.parse("image/*"), file_profile!!))builder.addFormDataPart(    "provider_documents[0][document]",    "1" + ".jpg",    RequestBody.create(MediaType.parse("image/*"), file_profile!!))我尝试了很多解决方案,但无法发布带有数据的图像数组。当我provider_documents从中删除时addFormDataPart工作正常。// @Multipart@POST(URLHelper.register)fun signUp2(@Body builder: RequestBody ): Observable<Registration>我如何发送Providers_document数组并且它在Postman.
查看完整描述

2 回答

?
富国沪深

TA贡献1790条经验 获得超9个赞

虚拟 api 接口。


 public interface ApiInterface {

        @Multipart

        @POST(URLHelper.register)

        Call<ModelProp> signUp2(@Part List<MultipartBody.Part> photos,

                          @PartMap Map<String, RequestBody> map;

    }

现在创建要像这样发布的数据。


Map<String, RequestBody> partMap = new HashMap<>();

List<MultipartBody.Part> images = new ArrayList<>();

partMap.put("device_id", createPartFromString(deviceId)); // add data which are common for all images like device_id, device_token, device_type etc.

..

..


for (int i=0; i < upFileList.size(); i++){

   images.add(prepareFilePart("provider_documents["+i+"][document]", imageFile));

   partMap.add("provider_documents["+i+"][expires_at]", createPartFromString(expiry)); // add image specific data. 

 ...

 ..

}

...

..

observable = apiInterface.signUp2(images, partMap).

createPartFromString方法


public RequestBody createPartFromString(String string) {

        return RequestBody.create(MultipartBody.FORM, string);

}

prepareFilePart方法


private MultipartBody.Part prepareFilePart(String partName, File file){

    RequestBody requestBody = RequestBody.create(MediaType.parse("image/*"), file);


    return MultipartBody.Part.createFormData(partName, file.getName(),requestBody);

}


查看完整回答
反对 回复 2023-03-31
?
慕斯王

TA贡献1864条经验 获得超2个赞

像这样使用它:-


// @Multipart

@POST(URLHelper.register)

fun signUp2(@Part builder: MultipartBody ): Observable<Registration>

更新 :-


  private void uploadToServer(String filePath) {

        showProgressDialog();

        Retrofit retrofit = RetrofitClient.getRetrofitClient(this);

        ApiInterface uploadAPIs = retrofit.create(ApiInterface.class);

        File file = new File(filePath);

        //compressor.setDestinationDirectoryPath()

        RequestBody fileReqBody = RequestBody.create(MediaType.parse("image/*"), file);

        MultipartBody.Part part = MultipartBody.Part.createFormData("fileUpload", file.getName(), fileReqBody);

        //RequestBody description = RequestBody.create(MediaType.parse("text/plain"), "image-type");

        RequestBody imgNameReqBody = RequestBody.create(MediaType.parse("multipart/form-data"), "B2B_" + System.nanoTime());


        uploadAPIs.uploadImage(imgNameReqBody, part).enqueue(new Callback<UploadImageRespose>() {

            @Override

            public void onResponse(@NonNull Call<UploadImageRespose> call, @NonNull retrofit2.Response<UploadImageRespose> response) {

                if (response.isSuccessful() && response.body() != null) {

                    if (response.body().getCODE().equalsIgnoreCase("SUCCESS")) {

                        Toast.makeText(Activity.this, "Profile Image Upload Succesfully", Toast.LENGTH_SHORT).show();

                    } else {

                        hideProgressDialog();

                        Toast.makeText(Activity.this, "Some Error  occurred, try again", Toast.LENGTH_SHORT).show();

                    }

                } else {

                    hideProgressDialog();

                }


            }


            @Override

            public void onFailure(@NonNull Call<UploadImageRespose> call, @NonNull Throwable t) {

                Timber.d(TAG, t.getMessage());

                hideProgressDialog();

                Toast.makeText(Activity.this, "Some Error  occurred, try again", Toast.LENGTH_SHORT).show();

            }

        });

    }

在您的界面中添加以下方法:-


    @Multipart

    @POST("Your Path Here")

    Call<UploadImageRespose> uploadImage(@Part("img_name") RequestBody img_name,

                                         @Part MultipartBody.Part file);


查看完整回答
反对 回复 2023-03-31
  • 2 回答
  • 0 关注
  • 216 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信