使用改造上传带有json对象的文件

时间:2018-10-22 09:56:57

标签: java android retrofit retrofit2

我要上传带有JSON对象的文件。我正在使用retrofit2,但收到400错误的请求。 我的请求示例使用curl:

curl -X POST http://localhost:8082/attachment -F filename=37.pdf -F 'data={"DocumentTypeID":2, "DocumentID":1, "Description":"описание","AttachmentTypeId":2}'

我也向邮递员提出了要求,它也可以工作: enter image description here

我的Java代码:

        Uri path = Uri.fromFile(file);
        RequestBody requestFile =
                RequestBody.create(
                        MediaType.parse(getMimeType(path)),
                        file
                );

        MultipartBody.Part body =
                MultipartBody.Part.createFormData("filename", file.getName(), requestFile);

        FileDescriptionObject fdo = new FileDescriptionObject();
        fdo.setDescription("test");
        fdo.setDocumentId(fileModel.Id);
        fdo.setDocumentTypeId(1);
        fdo.setAttachmentTypeId(2);
        Gson gson = new Gson();
        String ds1 = gson.toJson(fdo);

        RequestBody description =
                RequestBody.create(
                        MediaType.parse("text/plain"), ds1);

        Call<ResponseBody> call = activity.getAsyncHelper().getWebService().postFile(
                "http://localhost:8082/attachment",
                body,
                description);

我的API:

    @Multipart
    @POST
    Call<ResponseBody> postFile(@Url String url,
                                @Part MultipartBody.Part file,
                                @Part("data")RequestBody data);

我的日志:

D/OkHttp: --> POST http://localhost:8082/attachment
          Content-Type: multipart/form-data; boundary=520da8f2-5fac-4567-be0f-61618cc881bd
D/OkHttp: Content-Length: 468
D/OkHttp: --520da8f2-5fac-4567-be0f-61618cc881bd
D/OkHttp: Content-Disposition: form-data; name="filename"; filename="4.pdf"
          Content-Type: application/pdf
          Content-Length: 3
          323
          --520da8f2-5fac-4567-be0f-61618cc881bd
          Content-Disposition: form-data; name="data"
          Content-Transfer-Encoding: binary
          Content-Type: text/plain; charset=utf-8
          Content-Length: 77
          {"AttachmentTypeId":2,"Description":"test","DocumentId":4,"DocumentTypeId":1}
          --520da8f2-5fac-4567-be0f-61618cc881bd--
          --> END POST (468-byte body)

也许问题出在json数据中的这个附加标头中?我认为是因为在邮递员中没有添加它们。

1 个答案:

答案 0 :(得分:3)

更改

RequestBody description = RequestBody.create(MediaType.parse("text/plain"), ds1);

MultipartBody.Part description = MultipartBody.Part.createFormData("data", ds1);

,看看是否可行。还将您的API调用更改为

@Multipart
@POST
Call<ResponseBody> postFile(@Url String url,
                            @Part MultipartBody.Part file,
                            @Part MultipartBody.Part data);