Java实现从url路径下载文件到指定路径
代码实现:
1 /** 2 * 不带参数的get请求,如果状态码为200,则返回body,如果不为200,则返回null 3 * @param urlStr 被下载文件的url 4 * @param path 下载文件的路径和文件名 5 * @throws Exception 6 */ 7 public static void downloadFile(String urlStr, String path) { 8 try { 9 CloseableHttpClient httpClient = HttpClients.createDefault(); 10 // 声明 http get 请求 11 URL url = new URL(urlStr); 12 URI uri = new URI(url.getProtocol(), url.getHost(), url.getPath(), url.getQuery(), null); 13 HttpGet httpGet = new HttpGet(uri); 14 // 发起请求 15 CloseableHttpResponse response = httpClient.execute(httpGet); 16 17 // 判断状态码是否为200 18 if (response.getStatusLine().getStatusCode() == 200) { 19 // 返回响应体的内容 20 InputStream inputStream = response.getEntity().getContent(); 21 int index; 22 byte[] bytes = new byte[1024]; 23 FileOutputStream downloadFile = new FileOutputStream(path); 24 while ((index = inputStream.read(bytes)) != -1) { 25 downloadFile.write(bytes, 0, index); 26 downloadFile.flush(); 27 } 28 inputStream.close(); 29 downloadFile.close(); 30 31 } else if (response.getStatusLine().getStatusCode() == 500){ 32 33 throw new Exception(I18nUtil.getValueByKey("interfacecallfailed")); 34 } 35 } catch (Exception e) { 36 e.printStackTrace(); 37 } 38 }