Java Code Examples for java.net.http.HttpRequest.Builder#timeout()

The following examples show how to use java.net.http.HttpRequest.Builder#timeout() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: R2ServerClient.java    From r2cloud with Apache License 2.0 5 votes vote down vote up
private HttpRequest.Builder createRequest(String path) {
	Builder result = HttpRequest.newBuilder().uri(URI.create(hostname + path));
	result.timeout(Duration.ofMinutes(1L));
	result.header("User-Agent", R2Cloud.getVersion() + " [email protected]");
	result.header("Authorization", config.getProperty("r2cloud.apiKey"));
	return result;
}
 
Example 2
Source File: OreKitDataClient.java    From r2cloud with Apache License 2.0 4 votes vote down vote up
private void downloadAndSaveTo(String url, Path dst) throws IOException {
	Path tempPath = dst.getParent().resolve(dst.getFileName() + ".tmp").normalize();
	if (Files.exists(tempPath) && !Util.deleteDirectory(tempPath)) {
		throw new RuntimeException("unable to delete tmp directory: " + tempPath);
	}
	Files.createDirectories(tempPath);
	Builder result = HttpRequest.newBuilder().uri(URI.create(url));
	result.timeout(Duration.ofMillis(TIMEOUT));
	result.header("User-Agent", R2Cloud.getVersion() + " [email protected]");
	HttpRequest request = result.build();
	try {
		HttpResponse<InputStream> response = httpclient.send(request, BodyHandlers.ofInputStream());
		if (response.statusCode() != 200) {
			throw new IOException("invalid status code: " + response.statusCode());
		}
		Optional<String> contentType = response.headers().firstValue("Content-Type");
		if (contentType.isEmpty() || !contentType.get().equals("application/zip")) {
			throw new IOException("Content-Type is empty or unsupported: " + contentType);
		}
		try (ZipInputStream zis = new ZipInputStream(response.body())) {
			ZipEntry zipEntry = null;
			while ((zipEntry = zis.getNextEntry()) != null) {
				Path destFile = tempPath.resolve(zipEntry.getName()).normalize();
				if (!destFile.startsWith(tempPath)) {
					throw new IOException("invalid archive. zip slip detected: " + destFile);
				}
				if (zipEntry.isDirectory()) {
					Files.createDirectories(destFile);
					continue;
				}
				if (!Files.exists(destFile.getParent())) {
					Files.createDirectories(destFile.getParent());
				}
				Files.copy(zis, destFile, StandardCopyOption.REPLACE_EXISTING);
			}

			Files.move(tempPath, dst, StandardCopyOption.REPLACE_EXISTING);
		}
	} catch (InterruptedException e) {
		Thread.currentThread().interrupt();
		throw new RuntimeException(e);
	}
}