Programming Tutorials

(追記) (追記ここまで)

HttpClient

By: aathishankaran in JSP Tutorials on 2007年02月14日 [フレーム]

An HttpClient can be used to send requests and retrieve their responses. An HttpClient is created through a builder. The builder can be used to configure per-client state, like: the preferred protocol version ( HTTP/1.1 or HTTP/2 ), whether to follow redirects, a proxy, an authenticator, etc. Once built, an HttpClient is immutable, and can be used to send multiple requests.

Synchronous Example

 HttpClient client = HttpClient.newBuilder()
 .version(Version.HTTP_1_1)
 .followRedirects(Redirect.NORMAL)
 .connectTimeout(Duration.ofSeconds(20))
 .proxy(ProxySelector.of(new InetSocketAddress("proxy.example.com", 80)))
 .authenticator(Authenticator.getDefault())
 .build();
 HttpResponse response = client.send(request, BodyHandlers.ofString());
 System.out.println(response.statusCode());
 System.out.println(response.body()); 

Asynchronous Example

 HttpRequest request = HttpRequest.newBuilder()
 .uri(URI.create("https://java-samples.com/"))
 .timeout(Duration.ofMinutes(2))
 .header("Content-Type", "application/json")
 .POST(BodyPublishers.ofFile(Paths.get("file.json")))
 .build();
 client.sendAsync(request, BodyHandlers.ofString())
 .thenApply(HttpResponse::body)
 .thenAccept(System.out::println);



(追記) (追記ここまで)


Add Comment

JavaScript must be enabled for certain features to work
* Required information
1000

Comments

No comments yet. Be the first!
(追記) (追記ここまで)
(追記) (追記ここまで)

AltStyle によって変換されたページ (->オリジナル) /