import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Optional;
@RestController
public class MyController {
@GetMapping("/downloadFile")
public String downloadFile() throws IOException, InterruptedException {
// HttpClientのインスタンス作成
HttpClient client = HttpClient.newHttpClient();
// GETリクエストの作成
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://example.com/path/to/file")) // ダウンロード先のURLを指定
.build();
// レスポンスをファイルとして保存する
HttpResponse<Path> response = client.send(request, HttpResponse.BodyHandlers.ofFile(Paths.get("temp_file")));
// ステータスコードをチェック
if (response.statusCode() != 200) {
return "Failed to download file: HTTP status code " + response.statusCode();
}
// Content-Dispositionヘッダーからファイル名を取得
Optional<String> contentDisposition = response.headers().firstValue("Content-Disposition");
String fileName = "downloaded_file";
if (contentDisposition.isPresent() && contentDisposition.get().contains("filename=")) {
String[] parts = contentDisposition.get().split("filename=");
if (parts.length > 1) {
fileName = parts[1].replace("\"", "").trim();
}
}
// ファイルを保存
Path downloadedFilePath = Paths.get(fileName);
Files.move(Paths.get("temp_file"), downloadedFilePath);
return "File downloaded successfully: " + downloadedFilePath.toAbsolutePath();
}
}
Register as a new user and use Qiita more conveniently
- You get articles that match your needs
- You can efficiently read back useful information
- You can use dark theme