Last active
February 3, 2026 20:21
-
-
Save dacr/7b5f14fcae52018948b9067855b210fb to your computer and use it in GitHub Desktop.
http client using modern java default API / published by https://github.com/dacr/code-examples-manager #f988da9b-b5bb-4f80-b7bd-6165d7b90bff/f4f86d7795e088a3e454877c2123ae0a95991496
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // summary : http client using modern java default API | |
| // keywords : scala, java, @testable | |
| // publish : gist | |
| // authors : David Crosson | |
| // license : Apache License Version 2.0 (https://www.apache.org/licenses/LICENSE-2.0.txt) | |
| // id : f988da9b-b5bb-4f80-b7bd-6165d7b90bff | |
| // created-on : 2021-10-17T09:50:04+02:00 | |
| // managed-by : https://github.com/dacr/code-examples-manager | |
| // run-with : scala-cli $file | |
| // --------------------- | |
| //> using scala "3.4.2" | |
| // --------------------- | |
| def jsonGet(targetURI: String): java.net.http.HttpResponse[String] = { | |
| import java.net.http._ | |
| import java.net.http.HttpClient._ | |
| import java.net.http.HttpResponse._ | |
| import java.time.Duration | |
| import java.net._ | |
| val client = | |
| HttpClient | |
| .newBuilder() | |
| .version(Version.HTTP_1_1) | |
| .followRedirects(Redirect.NORMAL) | |
| .connectTimeout(Duration.ofSeconds(20)) | |
| //.proxy(ProxySelector.of(new InetSocketAddress("127.0.0.1", 3128))) | |
| //.authenticator(Authenticator.getDefault()) | |
| .build() | |
| val request = | |
| HttpRequest | |
| .newBuilder() | |
| .uri(URI.create(targetURI)) | |
| .timeout(Duration.ofMinutes(2)) | |
| .header("Content-Type", "application/json") | |
| .header("User-Agent", "Ammonite Script") | |
| .GET() | |
| .build(); | |
| client.send(request, BodyHandlers.ofString()) | |
| } | |
| println(jsonGet("https://httpbin.org/get").body()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment