java如何通过apachehttpclient上传文件?
我想上传一个文件,如下所述:http://docs.octoprint.org/en/master/api/files.html#upload-file-or-create-folder
我使用ApacheHttpClient发送post连接,但每当我启动该方法时,都不会发生任何事情,应用程序会毫无错误地陷入困境,但就是什么也不做
其他POST和GET请求正在工作,我不需要API密钥,因为我关闭了身份验证
CloseableHttpClient posterClient = HttpClients.createDefault();
HttpPost post = new HttpPost("http://localhost:5002/api/files/local");
post.setHeader("Host", "http://localhost:5002");
post.setHeader("Content-Type", "multipart/form-data; boundary=----WebKitFormBoundaryDeC2E3iWbTv1PwMC");
post.setHeader("X-Api-Key", "");
HttpEntity entity = MultipartEntityBuilder
.create()
.addBinaryBody("file", new File("/Users/florian/eclipse-workspace/docker-Client/src/main/java/test/dog3.gcode"), ContentType.create("multipart/form-data"), "dog.gcode")
.addTextBody("select", "true")
.addTextBody("print", "true")
.build();
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
entity.writeTo(bytes);
String content = bytes.toString();
StringEntity entity2 = new StringEntity(content, ContentType.APPLICATION_OCTET_STREAM);
entity2.setContentEncoding("application/octet-stream");
post.setEntity(entity2);
CloseableHttpResponse answer = posterClient.execute(post);
如果我打印帖子,我将获得(删除gcode说明):
RequestLine:POST http://localhost:5002/api/files/local HTTP/1.1
Header:boundary=----WebKitFormBoundaryDeC2E3iWbTv1PwMC;
Content:--JIDzHYxyG74480VXGugHYTI-7xe5OrZ8
Content-Disposition: form-data; name="file"; filename="dog.gcode"
Content-Type: multipart/form-data
Content-Transfer-Encoding: binary
M5
G90
G21
G1 F3000
G1 X18.0359 Y51.0881
M3 S90
G4 P0.3
--JIDzHYxyG74480VXGugHYTI-7xe5OrZ8
Content-Disposition: form-data; name="select"
Content-Type: text/plain; charset=ISO-8859-1
Content-Transfer-Encoding: 8bit
true
--JIDzHYxyG74480VXGugHYTI-7xe5OrZ8
Content-Disposition: form-data; name="print"
Content-Type: text/plain; charset=ISO-8859-1
Content-Transfer-Encoding: 8bit
true
--JIDzHYxyG74480VXGugHYTI-7xe5OrZ8--
所以。。。不完全是我想要的
# 1 楼答案
好的,现在我的代码看起来是这样的,而且可以正常工作。要删除内容类型编码等不必要的行,必须将ode设置为“浏览器兼容”