我要上传带有JSON对象的文件。我正在使用retrofit2,但收到400错误的请求。 我的请求示例使用curl:
curl -X POST http://localhost:8082/attachment -F filename=37.pdf -F 'data={"DocumentTypeID":2, "DocumentID":1, "Description":"описание","AttachmentTypeId":2}'
我的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数据中的这个附加标头中?我认为是因为在邮递员中没有添加它们。
答案 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);