使用PartMap中的Retrofit和WebKitFormBoundary将文件发送到服务器

时间:2017-12-31 12:56:27

标签: java android retrofit okhttp

我有一个由邮递员生成的查询,用于向我的服务器发送文件和一些信息。它在我的程序中工作正常。

  MediaType mediaType = MediaType.parse("multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW");
        RequestBody body = RequestBody.create(mediaType,
                "------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"filename\"; filename=\"C:\\testFile.doc\"\r\nContent-Type: application/msword\r\n\r\n\r\n" +
                        "------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"id\"\r\n\r\n7\r\n" +
                        "------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"type\"\r\n\r\n3\r\n" +
                        "------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"note\"\r\n\r\nafejhejfh\r\n" +
                        "------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"list[0][id]\"\r\n\r\n1\r\n" +
                        "------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"list[0][is_checked]\"\r\n\r\n0\r\n" +
                        "------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"list[0][filename]\"; filename=\"C:\\test.pdf\"\r\nContent-Type: application/pdf\r\n\r\n\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW--");

改造方法:

@Headers({"Accept: application/json", "content-type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW"})
@POST("api/save")
Call<SaveResponse> save(@Header("Authorization") String authorization,
                                   @Body RequestBody map);

首次面对webkitformboundary并需要将上面的示例更改为动态创建的Partmap。因为需要在另一个列表的循环中添加一些参数。 我尝试使用类似下面的示例生成partmap并添加&#34; WebKitFormBoundary7MA4YWxkTrZu0gW&#34;像api文档中写的标题

  --header 'Authorization: {{authorization}}' \
  --header 'content-type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW' \

以下代码从服务器返回422错误

查询地图。

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

RequestBody file = null;
if (file != null) {
    file = RequestBody.create(MediaType.parse("application/msword"), testFile);
    requestMap.put("filename", file);
}

RequestBody id = RequestBody.create(MediaType.parse("text/plain"), "18");
RequestBody type = RequestBody.create(MediaType.parse("text/plain"), "3");
RequestBody notes = RequestBody.create(MediaType.parse("text/plain"), notesTextArea.getText());
RequestBody list0id = RequestBody.create(MediaType.parse("text/plain"), "1");
RequestBody list0is_checked = RequestBody.create(MediaType.parse("text/plain"), "0");


RequestBody pdfFilename = null;
if (pdfFile != null) {
    pdfFilename  = RequestBody.create(MediaType.parse("application/pdf"), pdfFile);
    requestMap.put("list[0][filename]", pdfFilename );
}

requestMap.put("file", file);
requestMap.put("id", id);
requestMap.put("type", type);
requestMap.put("notes", notes);
requestMap.put("list[0]id", list0id);
requestMap.put("list[0]is_checked", list0is_checked);

改造方法:

  @Multipart
    @Headers({"Accept: application/json", "content-type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW"})
    @POST("api/save")
    Call<SaveResponse> save(@Header("Authorization") String authorization,
                                       @PartMap Body map);

所以需要任何帮助来了解如何将WebKitFormBoundary7MA4YWxkTrZu0gW和其他所需信息放入我的Partmap。

提前感谢您提供任何帮助

P.S。新年快乐编码员)

1 个答案:

答案 0 :(得分:0)

所以我以这种方式解决了这个问题

请求我的服务器。没有标题的请求&#34; content-type:multipart / form-data;边界= ---- WebKitFormBoundary7MA4YWxkTrZu0gW&#34;&#34;在API文档中描述。

  private void fillQuery() {

        fileListPart = new ArrayList<>();
        MultipartBody.Part filePart = null;
        if (mainFile != null) {
            if (mainFile.getName().endsWith(".pdf")) {
                filePart = MultipartBody.Part.createFormData("filename", mainFile.getName(), RequestBody.create(MediaType.parse("application/pdf"), mainFile));
            } else if (mainFile.getName().endsWith(".doc") || mainFile.getName().endsWith(".docx")) {
                filePart = MultipartBody.Part.createFormData("filename", mainFile.getName(), RequestBody.create(MediaType.parse("application/msword"), mainFile));
            }
            fileListPart.add(filePart);
        }

        requestBodyMap = new HashMap<>();
        RequestBody id = RequestBody.create(MediaType.parse("text/plain"), "id");
        RequestBody type = RequestBody.create(MediaType.parse("text/plain"), "type");
        RequestBody notes = RequestBody.create(MediaType.parse("text/plain"), "notes");

        requestBodyMap.put("id", id);
        requestBodyMap.put("type", type);
        requestBodyMap.put("notes", notes);

        for (int i = 0; i < dynamicCollectionWirhParameters.size(); i++) {
            String prefix = "list[";
            String checkIdParameter = "][id]";
            String checkIsCheckedParameter = "][is_checked]";
            String checkFileParameter = "][filename]";

            RequestBody checklist_id = RequestBody.create(MediaType.parse("text/plain"), "2");//id
            RequestBody is_checked = RequestBody.create(MediaType.parse("text/plain"), "1"); // server convert 1 and 0 to boolean value
            requestBodyMap.put(prefix + i + checkIdParameter, checklist_id);
            requestBodyMap.put(prefix + i + checkIsCheckedParameter, is_checked);

            if (dynamicCollectionFileCollection.get(i) != null) {
                File tempFile = dynamicCollectionFileCollection.get(i);
                filePart = null;
                if (tempFile.getName().endsWith(".pdf")) {
                    filePart = MultipartBody.Part.createFormData(prefix + i + checkFileParameter, dynamicCollectionFileCollection.get(i).getName(), RequestBody.create(MediaType.parse("application/pdf"), dynamicCollectionFileCollection.get(i)));
                } else if (dynamicCollectionFileCollection.get(i).getName().endsWith(".doc") || dynamicCollectionFileCollection.get(i).getName().endsWith(".docx")) {
                    filePart = MultipartBody.Part.createFormData(prefix + i + checkFileParameter, dynamicCollectionFileCollection.get(i).getName(), RequestBody.create(MediaType.parse("application/msword"), dynamicCollectionFileCollection.get(i)));
                }
                fileListPart.add(filePart);
            }
        }

    }

动态填写我们的查询

private void saveDatas() {
        fillQuery();

        Call<SaveResponse> sendDatasCall = DependenciesStorage.getRetrofitService().save(
                DependenciesStorage.getAuthorizationKey(),
                requestBodyMap, fileListPart);

        sendDatasCall.enqueue(new Callback<SaveResponse>() {
            @Override
            public void onResponse(Call<SaveResponse> call, Response<SaveResponse> response) {
                if (response.isSuccessful()) {

                  } else {

                 }
            }

            @Override
            public void onFailure(Call<SaveResponse> call, Throwable throwable) {
            }
        });

    }

将我们的数据发送到服务器

master

看起来很简单)但我花了差不多两天才找到它