Last active
May 25, 2024 10:20
-
-
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/a9820d422737c484c1e77b5fd2dc791d7a499b87
This file contains 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 NON-AI License Version 2.0 (https://raw.githubusercontent.com/non-ai-licenses/non-ai-licenses/main/NON-AI-APACHE2) | |
// 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