Java Spring: методы получения файла по URL-адресу

Чтобы получить файл по URL-адресу в приложении Java Spring, вы можете использовать несколько методов. Вот некоторые распространенные подходы:

  1. Использование классов java.net.URLи java.io:

    import java.io.BufferedInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.net.URL;
    public class FileDownloader {
       public static void main(String[] args) {
           String fileURL = "http://example.com/file.pdf";
           String saveDir = "/path/to/save/directory/";
           try {
               URL url = new URL(fileURL);
               InputStream inputStream = new BufferedInputStream(url.openStream());
               FileOutputStream fileOutputStream = new FileOutputStream(saveDir + "file.pdf");
               byte[] buffer = new byte[1024];
               int bytesRead;
               while ((bytesRead = inputStream.read(buffer, 0, buffer.length)) != -1) {
                   fileOutputStream.write(buffer, 0, bytesRead);
               }
               fileOutputStream.close();
               inputStream.close();
               System.out.println("File downloaded successfully.");
           } catch (IOException e) {
               e.printStackTrace();
           }
       }
    }
  2. Использование библиотеки Apache HttpClient:

    import org.apache.http.client.methods.CloseableHttpResponse;
    import org.apache.http.client.methods.HttpGet;
    import org.apache.http.impl.client.CloseableHttpClient;
    import org.apache.http.impl.client.HttpClients;
    import org.apache.http.util.EntityUtils;
    public class FileDownloader {
       public static void main(String[] args) {
           String fileURL = "http://example.com/file.pdf";
           String saveDir = "/path/to/save/directory/";
           try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
               HttpGet httpGet = new HttpGet(fileURL);
               CloseableHttpResponse response = httpClient.execute(httpGet);
               InputStream inputStream = response.getEntity().getContent();
               FileOutputStream fileOutputStream = new FileOutputStream(saveDir + "file.pdf");
               byte[] buffer = new byte[1024];
               int bytesRead;
               while ((bytesRead = inputStream.read(buffer, 0, buffer.length)) != -1) {
                   fileOutputStream.write(buffer, 0, bytesRead);
               }
               fileOutputStream.close();
               inputStream.close();
               response.close();
               System.out.println("File downloaded successfully.");
           } catch (IOException e) {
               e.printStackTrace();
           }
       }
    }
  3. Использование Spring RestTemplate(устарело в Spring 5):

    import org.springframework.http.HttpHeaders;
    import org.springframework.http.ResponseEntity;
    import org.springframework.web.client.RestTemplate;
    public class FileDownloader {
       public static void main(String[] args) {
           String fileURL = "http://example.com/file.pdf";
           String saveDir = "/path/to/save/directory/";
           RestTemplate restTemplate = new RestTemplate();
           ResponseEntity<byte[]> response = restTemplate.getForEntity(fileURL, byte[].class);
           if (response.getStatusCode().is2xxSuccessful()) {
               byte[] fileData = response.getBody();
               HttpHeaders headers = response.getHeaders();
               // Save the fileData to the saveDir
               // ...
               System.out.println("File downloaded successfully.");
           }
       }
    }

Обратите внимание, что в этих примерах основное внимание уделяется загрузке файлов с заданного URL-адреса с использованием различных подходов в Java Spring. Возможно, вам придется адаптировать код в соответствии с вашими конкретными требованиями.