|
1 | 1 | package com.stefanbratanov.sofiasupermarketsapi.common
|
2 | 2 |
|
| 3 | +import java.io.FileOutputStream |
3 | 4 | import java.net.URL
|
4 |
| -import java.nio.file.Files |
5 | 5 | import java.nio.file.Path
|
6 |
| -import java.nio.file.StandardCopyOption |
| 6 | +import kotlin.io.path.fileSize |
| 7 | +import org.apache.hc.client5.http.classic.methods.HttpGet |
| 8 | +import org.apache.hc.client5.http.impl.classic.HttpClients |
7 | 9 |
|
8 | 10 | fun copyURLToFile(source: URL, destination: Path): Long {
|
9 |
| - val connection = source.openConnection() |
10 |
| - // Set a Browser-like User-Agent |
11 |
| - connection.setRequestProperty( |
12 |
| - "User-Agent", |
13 |
| - "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/139.0.0.0 Safari/537.36", |
14 |
| - ) |
15 |
| - return connection.inputStream.use { inputStream -> |
16 |
| - Files.copy(inputStream, destination, StandardCopyOption.REPLACE_EXISTING) |
| 11 | + val client = HttpClients.createDefault() |
| 12 | + val request = |
| 13 | + HttpGet(source.toURI()).apply { |
| 14 | + setHeader( |
| 15 | + "User-Agent", |
| 16 | + "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/139.0.0.0 Safari/537.36", |
| 17 | + ) |
| 18 | + } |
| 19 | + |
| 20 | + client.execute(request) { |
| 21 | + it.entity!!.content.use { inputStream -> |
| 22 | + FileOutputStream(destination.toFile()).use { outputStream -> |
| 23 | + inputStream.copyTo(outputStream) |
| 24 | + } |
| 25 | + } |
17 | 26 | }
|
| 27 | + |
| 28 | + return destination.fileSize() |
18 | 29 | }
|
0 commit comments