java - HttpClient - 使用 Tomcat Webdav 上传 JAR 文件会导致“jarfile 无效或损坏”
问题描述
当我尝试启动它时,我无法使用 Webdav 和 Apache HTTPClient 上传 JAR 文件而不会导致“无效或损坏的 jarfile”。
这是我的设置:
- Webdav 服务器,在外部目录上使用 tomcat 8.5(在 $CATALINA_HOME/conf/Catalina/localhost/webdav.xml 中定义)
- Apache HTTP 客户端 (org.apache.httpcomponents:httpclient:4.5.5)
- 使用 HTTP 客户端上传文件的自定义 Maven 插件
构建 JAR 后,使用自定义 maven 插件(内部使用 HTTP 客户端)上传文件。
如果我尝试使用 HTTP 客户端将文件上传到远程服务器,则会导致损坏。但是如果我使用 curl 命令发送完全相同的文件,我可以毫无问题地启动 Jar
curl -u <user>:<pass> -T <myjar>.jar http://<remotehost>/<myjar>.jar
以下是使用 HTTP 客户端的示例代码:
class FileSender {
public static void main(String[] args) {
// [...]
RequestConfig.Builder cfg = RequestConfig.copy(RequestConfig.DEFAULT);
cfg = cfg.setConnectTimeout(timeout)
.setConnectionRequestTimeout(timeout)
.setSocketTimeout(timeout);
CredentialsProvider credentialsProvider = authentication.credentials();
HttpClientBuilder builder = HttpClientBuilder.create()
.setDefaultRequestConfig(cfg.build())
.setDefaultCredentialsProvider(credentialsProvider);
try(CloseableHttpClient client = builder.build()) {
HttpPut httpPut = new HttpPut("http://<remote>/<myJar>.jar");
httpPut.setEntity(MultipartEntityBuilder.create()
.addBinaryBody("file", new File("path/to/<myJar>.jar"))
.build());
try (CloseableHttpResponse response = client.execute(httpPut)) {
// Check response HTTP status
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
你有什么可能导致我的问题吗?
编辑:如果我使用 HTTP 客户端和 CURL,MD5 哈希值似乎不同,但 CURL 和 FTP 副本共享相同的哈希值。
解决方案
这是使用 HttpClient 上传任何文件的方式:
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
HttpEntity requestEntity = MultipartEntityBuilder.create().addBinaryBody("file", new File("myfile")).build();
HttpPost post = new HttpPost("http://...");
post.setEntity(requestEntity);
try (CloseableHttpResponse response = httpClient.execute(post)) {
System.out.print(response.getStatusLine());
}
通常 POST 方法用于上传表单或文件内容。
推荐阅读
- geometry - 使用半正弦曲率绘制圆形或散点图层
- matplotlib - Polarplot 误差线 maplotlib
- python - 遗留数据库中的解析日期问题 | Django 检查数据库
- swift - 如何为自定义图像或媒体重新格式化阵列中的系统图像代码?
- angular - 访问和修改 HashMap 中数组中的值:Typescript
- vue.js - 将 Vue 组件加载为简码
- django - 一个 Django 应用程序/模型到多个数据库
- javascript - 如何将键值对添加到处于功能组件状态的对象中
- python - 如何使用 Python 和 pexpect 在多个会话中运行 linux 可执行文件
- r - 使用 R 中的正参数输入优化函数