我想上傳帶有 JSON 對象的文件。我正在使用 Retrofit2,但收到 400 Bad request。我使用 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-61618cc881bdD/OkHttp: Content-Length: 468D/OkHttp: --520da8f2-5fac-4567-be0f-61618cc881bdD/OkHttp: Content-Disposition: form-data; name="filename"; filename="4.pdf" Content-Type: application/pdf Content-Length: 3 323 --520da8f2-5fac-4567-be0f-61618cc881bd也許問題出在這個來自 json 數據的附加頭文件中?我認為是因為在郵遞員中沒有添加它們。
1 回答

慕尼黑8549860
TA貢獻1818條經驗 獲得超11個贊
改變
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);
添加回答
舉報
0/150
提交
取消