[英]File upload with postman works but fails with Apache HttpClient
I'm working with an external REST API on a test system.我正在测试系统上使用外部 REST API。 There is an upload path I'm trying to implement and I am using the Apache HTTPClient.
我正在尝试实现一个上传路径,并且我正在使用 Apache HTTPClient。 I tried it with the following postman configuration and it works perfectly:
我使用以下邮递员配置进行了尝试,效果很好:
The upload works fine like that.上传工作正常。
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPut request = new HttpPut("../upload") // placeholder url, not the real one
request.setHeader("Content-type", "multipart/form-data");
request.setHeader(HttpHeaders.AUTHORIZATION, "HEY I AM A TOKEN");
FileBody fileBody = new FileBody(new File("dummy.pdf"), ContentType.create("application/pdf"));
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addPart("file", fileBody);
request.setEntity(builder.build());
CloseableHttpResponse response = httpClient.execute(request);
I always get a specific error from the rest api:我总是从其余的 api 中得到一个特定的错误:
File could not have been parsed
The documentation of the upload path mentions the following details:上传路径的文档中提到了以下细节:
I think I do every point of this list in my request - so what is the difference between the postman request and my own java http request?我想我在我的请求中做了这个列表的每一点 - 那么邮递员请求和我自己的 java http 请求有什么区别?
What do I miss?我想念什么?
EDIT:编辑:
The same code with OkHTTP works.与 OkHTTP 相同的代码有效。 Still don't know why it does not work with Apache HttpClient.
仍然不知道为什么它不适用于 Apache HttpClient。
OkHttpClient testClient = new OkHttpClient();
File testfile = new File("dummy.pdf");
RequestBody body = new MultipartBuilder().type(MultipartBuilder.FORM).addFormDataPart("file","dummy.pdf",
RequestBody.create(MediaType.parse("application/pdf"),testfile)).build();
Request testreq = new Request.Builder()
.url("../upload")
.header("Authorization", "HI I AM A TOKEN")
.put(body)
.build();
Response testres = testClient.newCall(testreq).execute();
I had to remove this line我不得不删除这一行
request.setHeader("Content-type", "multipart/form-data");
to make it work.使其工作。 I dont really know why so if someone can help me out with this and give some explanation I'm up for it.
我真的不知道为什么,所以如果有人能帮我解决这个问题并给出一些解释,我愿意。 For the moment I'm happy because it works now.
目前我很高兴,因为它现在有效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.