服务器端:
@RequestMapping("/jar-file")
public void downLoadFile(String downloadFilePath, HttpServletResponse response) throws IOException {
File file = new File(filePath + downloadFilePath);
if (!file.exists()) {
return;
}
InputStream in = new FileInputStream(file);
byte[] body = new byte[in.available()];
in.read(body);
in.close();
OutputStream out = new BufferedOutputStream(response.getOutputStream());
response.setContentType("application/x-java-archive");
response.addHeader("Content-Disposition", "attachment;filename=mallwash_agent.jar");
out.write(body);
out.flush();
out.close();
}
客户端:
使用apache.commons.client
public static void main(String[] args) {
try {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet request = new HttpGet(url);
CloseableHttpResponse response = httpClient.execute(request);
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
File file = new File("/home/hao/开发/test.jar");
if (!file.exists()) {
file.createNewFile();
}
OutputStream os = new FileOutputStream(file);
byte[] buffer = new byte[4096];
int n = 0;
while (-1 != (n = is.read(buffer))) {
os.write(buffer, 0, n);
}
// IOUtils.copy(is, os);可使用apache工具
os.flush();
os.close();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
不能使用:
InputStream in = entity.getContent();
byte[] body = new byte[in.available()];
in.read(body);
估计是使用网络传输无法直接获取所有输入流内容