Skip to content

Instantly share code, notes, and snippets.

@dacr
Last active April 2, 2023 10:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dacr/7b5f14fcae52018948b9067855b210fb to your computer and use it in GitHub Desktop.
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/b728879f783b526523589c3e9f5ba419d02eddf0
// 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.1.1"
// ---------------------
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