【发布时间】:2012-09-06 10:31:53
【问题描述】:
我需要将 tar.gzip 文件从一个 java 应用程序(通过 Servlet)发送到另一个 - 我正在使用 HTTP 客户端和 MultipartEntity 来实现这一点。
在文件传输过程中,文件的大小似乎翻了一番 - 好像它正在被解压缩 - 并且它不再被识别为 tar.gz 或 tar 文件。
这里是发送方法:
HttpClient http = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
MultipartEntity multipart = new MultipartEntity();
ContentBody fileContent = new FileBody(file, "application/octet-stream");
ContentBody pathContent = new StringBody(file.getAbsolutePath());
multipart.addPart("package", fileContent);
multipart.addPart("path", pathContent);
post.setEntity(multipart);
HttpResponse response = null;
try {
response = http.execute(post);
StringWriter sw = new StringWriter();
IOUtils.copy(response.getEntity().getContent(), sw);
} catch (Exception ex){
log.error("Unable to POST to ["+url+"].",ex);
}
return result;
这是上面代码发布到的 servlet 方法:
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
log.info("File transfer request received, collecting file information and saving to server.");
Part filePart = req.getPart("package");
Part filePathPart = req.getPart("path");
StringWriter sw = new StringWriter();
IOUtils.copy(filePathPart.getInputStream(), sw);
String path = sw.getBuffer().toString();
File outputFile = new File(path);
FileWriter out = new FileWriter(outputFile);
IOUtils.copy(filePart.getInputStream(), out);
log.info("File ["+path+"] has been saved to the server.");
out.close();
sw.close();
}
我不是这方面的专家 - 而且 Google 似乎没有太多帮助...任何帮助都会很棒。
谢谢, 皮特
【问题讨论】:
标签: java servlets httpclient