1

このようにJava 11でhttpclientを使用して単一のメディアファイルをダウンロードできます

public class Httptest {
    
    private static HttpClient client = HttpClient.newBuilder().build();
            
    public static void main(String[] args) throws Exception {
        File fts = new File("P:/sample.ts");  //Destination of downloaded file
        fts.createNewFile();
        URI url = new URI("File url here"); //File Url
        
        HttpRequest request = HttpRequest.newBuilder()   //Creating HttpRequest using Builder class
                .GET()
                .uri(url)
                .build();
        Path file = Path.of("P:/samp.ts");
        //BodyHandlers class has methods to handle the response body
        // In this case, save it as a file (BodyHandlers.ofFile())
        HttpResponse<Path> response = client.send(request,BodyHandlers.ofFile(file)); 
    }
}

上記のコード スニペットは、URL から .ts ファイルをダウンロードします。そして、正常にダウンロードされます。

今、私はURLのリストを持っていますList<URI> urls. URL のリストに対して非同期呼び出しを行い、Executor service. 私が立ち往生している場所は、応答のリストを単一のファイルに書き込む方法です。

これまでに書いたコード:

public class httptest{
    
   // Concurrent requests are made in 4 threads
   private static ExecutorService executorService = Executors.newFixedThreadPool(4); 

   //HttpClient built along with executorservice
   private static HttpClient client = HttpClient.newBuilder() 
            .executor(executorService)
            .build();
    
   public static void main(String[] args) throws Exception{
        File fts = new File("P:/Spyder_directory/sample.ts");
        fts.createNewFile();
        List<URI> urls = Arrays.asList(
                         new URI("Url of file 1"),
                         new URI("Url of file 2"),
                         new URI("Url of file 3"),
                         new URI("Url of file 4"),
                         new URI("Url of file 5"));
        
        
        List<HttpRequest> requests = urls.stream()
                .map(HttpRequest::newBuilder)
                .map(requestBuilder -> requestBuilder.build())
                .collect(toList());
        Path file = Path.of("P:/Spyder_directory/sample.ts");
        List<CompletableFuture<HttpResponse<Path>>> results = requests.stream()
                .map(individual_req -> client.sendAsync(individual_req,BodyHandlers.ofFile(file)))
                .collect(Collectors.toList());
   }
}

実行の最後に作成されたファイルsample.tsには、行われた要求の応答がありません。私の問題の要点がわかれば、この問題の代替ソリューションを提案できる人はいますか?

4

1 に答える 1