public void downloadFile(String url, File targetFile) { CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpResponse response = null; try { HttpGet httpGet = new HttpGet(url); response = httpClient.execute(httpGet); StatusLine statusLine = response.getStatusLine(); if (statusLine.getStatusCode() == 200) { FileOutputStream outputStream = new FileOutputStream(targetFile); InputStream inputStream = response.getEntity().getContent(); byte[] buff = new byte[4096]; boolean var10 = false; int counts; while((counts = inputStream.read(buff)) != -1) { outputStream.write(buff, 0, counts); } outputStream.flush(); outputStream.close(); } } catch (Exception var19) { ; } finally { try { if (response != null) { response.close(); } if (httpClient != null) { httpClient.close(); } } catch (IOException var18) { var18.printStackTrace(); } } }
downloadFile
最新推荐文章于 2025-06-11 16:51:37 发布
本文介绍了一个使用Java实现的HTTP文件下载方法。通过CloseableHttpClient进行网络请求,利用HttpGet获取指定URL的内容,并将其写入到本地文件中。文章详细展示了如何处理网络响应、文件流操作及异常情况。
633

被折叠的 条评论
为什么被折叠?



