无法在Android中的Retrofit 2中同时发送标题和多部分

问题描述 投票:1回答:1

这是我用于多次上传到服务器的代码。这种格式在POSTMAN中工作正常,而不是使用retrofit2。有谁能够帮我

@Multipart
@POST("/api/answers/save")
Call<ResponseBody> upload(@Header("Authorization") String 
authorization,@Part("input_answer") RequestBody answer_string,@Part 
  List<MultipartBody.Part> files); 

检查一下

@NonNull
private RequestBody createPartFromJsonString(String json_answers_string) {
    return RequestBody.create(
            okhttp3.MultipartBody.FORM, json_answers_string);
}

检查一下,使用它将文件转换为multipart body

@NonNull
private MultipartBody.Part prepareFilePart(String attachment_name, String absolute_path) {
 File file = new File(absolute_path);


    RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
    return MultipartBody.Part.createFormData(attachment_name, file.getName(), requestFile);
}

这用于多次上传

private void multipartUploadAudit(JSONObject json_object, List<String> FileNameWithAbsolutePath) {
    progressBar.setVisibility(View.VISIBLE);
    //convert jsonobject to string
    Gson gson = new Gson();
    String answers_string_json_obj = gson.toJson(json_object);


    APIService mAPIService = ApiUtils.getAPIService();
    List<MultipartBody.Part> parts = new ArrayList<>();
    // add dynamic
    for (int i = 0; i < FileNameWithAbsolutePath.size(); i++) {
        String name = FileNameWithAbsolutePath.get(i).substring(FileNameWithAbsolutePath.get(i).lastIndexOf("/") + 1);
        String names[] = name.split("\\.");
        parts.add(prepareFilePart(names[0], FileNameWithAbsolutePath.get(i)));
    }
    // add another part within the multipart request
    RequestBody answer_string = createPartFromJsonString(answers_string_json_obj);

    // finally, execute the request
    Call<ResponseBody> call = mAPIService.upload("Bearer " + sharedPrefUserData.getUserData().getAuthToken(), answer_string, parts);
    // Call<ResponseBody> call = mAPIService.upload( description, parts);
    call.enqueue(new Callback<ResponseBody>() {
        @Override
        public void onResponse(Call<ResponseBody> call, retrofit2.Response<ResponseBody> response) {
            progressBar.setVisibility(View.GONE);
            if (response.isSuccessful()) {
                response.body(); // do something with that
                Toast.makeText(AuditQuestionsLandingScreen.this, response.body().toString(), Toast.LENGTH_SHORT).show();
            } else {
                response.errorBody(); // do something with that
                Toast.makeText(AuditQuestionsLandingScreen.this, response.errorBody().toString(), Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onFailure(Call<ResponseBody> call, Throwable t) {
            progressBar.setVisibility(View.GONE);
            internetConnectionChecker.serverErrorAlert();
            Log.v("Upload_error:", t.getMessage());
            Toast.makeText(AuditQuestionsLandingScreen.this, t.getMessage(), Toast.LENGTH_SHORT).show();

        }
    });
}
android retrofit retrofit2
1个回答
0
投票

经过长时间的奋斗,我得到了答案。我通过使用gson将jsonobject转换为字符串而犯了一个错误。它添加了我的字符串{{nameValuePairs“:{}}

所以我用过这个。 RequestBody.create(MediaType.parse(“multipart / form- data”),String.valueOf(json_object))

© www.soinside.com 2019 - 2024. All rights reserved.