问题详情:就是我想下载附件并保存到本地。我在网页点击附件会直接弹出下载框问是否保存文件,我将弹出下载文件的 url,给获取下载,并通过以下方法去操作,文件可以保存,但已经损坏,文件大小都为 4kb,打不开,文件名我能正确获取
//通过 url 下载资源到本地
public static final Boolean downLoadSourceByUrl(String url, String fileName){
HttpGet httpGet = null;
String localFileName = null;
String fileOriName = null;
System.out.println("进入保存文件这");
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
// 这里我设置了超时时间的配置,也可以不设
RequestConfig timeoutConfig = RequestConfig.custom()
.setConnectTimeout(5000).setConnectionRequestTimeout(1000)
.setSocketTimeout(5000).build();
// 本例的文件下载接口是直接返回的文件流
httpGet = new HttpGet(url);
httpGet.setConfig(timeoutConfig);
httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:50.0) Gecko/20100101 Firefox/50.0"); // 设置请求头消息 User-Agent
HttpResponse downLoadResponse = httpClient.execute( httpGet);
StatusLine statusLine = downLoadResponse.getStatusLine();
// 响应码
int statusCode = statusLine.getStatusCode();
// 请求成功
if (statusCode == 200) {
System.out.println("请求成功");
// 获取接口返回的文件流
HttpEntity entity = downLoadResponse.getEntity();
InputStream input = entity.getContent();
// 本例是储存到本地文件系统,fileRealName 为你想存的文件名称
File dest = new File("d:/img/"+fileName);
OutputStream output = new FileOutputStream(dest);
int len = 0;
byte[] ch = new byte[10240];
while ((len = input.read(ch)) != -1) {
output.write(ch, 0, len);
}
}
} catch (Exception e) {
System.out.println(e+"在工具类这");
return false;
} finally {
if ( httpGet != null) {
httpGet.releaseConnection();
}
}
return true;
}