Val*_*aal 2 java android retrofit retrofit2
我想上传带有 JSON 对象的文件。我正在使用 Retrofit2,但收到 400 Bad request。\n我使用curl的请求示例:
\n\ncurl -X POST http://localhost:8082/attachment -F filename=37.pdf -F \'data={"DocumentTypeID":2, "DocumentID":1, "Description":"\xd0\xbe\xd0\xbf\xd0\xb8\xd1\x81\xd0\xb0\xd0\xbd\xd0\xb8\xd0\xb5","AttachmentTypeId":2}\'\nRun Code Online (Sandbox Code Playgroud)\n\n\n\n我的Java代码:
\n\n Uri path = Uri.fromFile(file);\n RequestBody requestFile =\n RequestBody.create(\n MediaType.parse(getMimeType(path)),\n file\n );\n\n MultipartBody.Part body =\n MultipartBody.Part.createFormData("filename", file.getName(), requestFile);\n\n FileDescriptionObject fdo = new FileDescriptionObject();\n fdo.setDescription("test");\n fdo.setDocumentId(fileModel.Id);\n fdo.setDocumentTypeId(1);\n fdo.setAttachmentTypeId(2);\n Gson gson = new Gson();\n String ds1 = gson.toJson(fdo);\n\n RequestBody description =\n RequestBody.create(\n MediaType.parse("text/plain"), ds1);\n\n Call<ResponseBody> call = activity.getAsyncHelper().getWebService().postFile(\n "http://localhost:8082/attachment",\n body,\n description);\nRun Code Online (Sandbox Code Playgroud)\n\n我的API:
\n\n @Multipart\n @POST\n Call<ResponseBody> postFile(@Url String url,\n @Part MultipartBody.Part file,\n @Part("data")RequestBody data);\nRun Code Online (Sandbox Code Playgroud)\n\n我的日志:
\n\nD/OkHttp: --> POST http://localhost:8082/attachment\n Content-Type: multipart/form-data; boundary=520da8f2-5fac-4567-be0f-61618cc881bd\nD/OkHttp: Content-Length: 468\nD/OkHttp: --520da8f2-5fac-4567-be0f-61618cc881bd\nD/OkHttp: Content-Disposition: form-data; name="filename"; filename="4.pdf"\n Content-Type: application/pdf\n Content-Length: 3\n 323\n --520da8f2-5fac-4567-be0f-61618cc881bd\n Content-Disposition: form-data; name="data"\n Content-Transfer-Encoding: binary\n Content-Type: text/plain; charset=utf-8\n Content-Length: 77\n {"AttachmentTypeId":2,"Description":"test","DocumentId":4,"DocumentTypeId":1}\n --520da8f2-5fac-4567-be0f-61618cc881bd--\n --> END POST (468-byte body)\nRun Code Online (Sandbox Code Playgroud)\n\n也许问题出在 json 数据的附加标头中?我认为是这样,因为在邮递员中它们没有被添加。
\n改变
RequestBody description = RequestBody.create(MediaType.parse("text/plain"), ds1);
Run Code Online (Sandbox Code Playgroud)
到
MultipartBody.Part description = MultipartBody.Part.createFormData("data", ds1);
Run Code Online (Sandbox Code Playgroud)
看看是否有效。还将您的 API 调用更改为
@Multipart
@POST
Call<ResponseBody> postFile(@Url String url,
@Part MultipartBody.Part file,
@Part MultipartBody.Part data);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3604 次 |
| 最近记录: |