Java 11 Tutorial
Java Other Versions Tutorials
Java 11 Useful Resources
Selected Reading
- Java 11 - Removed/Deprecated API
- Java 11 - Nest Based Access
- Java 11 - var in lambda
- Java 11 - Not Predicate
- Java 11 - Optional Class
- Java 11 - File APIs
- Java 11 - Collections to Array
- Java 11 - String APIs
- Java 11 - Compile free Launch
- Java 11 - Standard HttpClient
- Java 11 - Environment Setup
- Java 11 - Overview
- Java 11 - Home
Java Other Versions Tutorials
- Java 16 Tutorial
- Java 15 Tutorial
- Java 14 Tutorial
- Java 13 Tutorial
- Java 12 Tutorial
- Java 10 Tutorial
- Java 9 Tutorial
- Java 8 Tutorial
- Java Tutorial
Java 11 Useful Resources
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
Java 11 - Standard HttpClient
Java 11 - Standard HttpCpent
An enhanced HttpCpent API was introduced in Java 9 as an experimental feature. With Java 11, now HttpCpent is a standard. It is recommended to use instead of other HTTP Cpent APIs pke Apache Http Cpent API. It is quite feature rich and now Java based apppcations can make HTTP requests without using any external dependency.
Steps
Following are the steps to use an HttpCpent.
Create HttpCpent instance using HttpCpent.newBuilder() instance
Create HttpRequest instance using HttpRequest.newBuilder() instance
Make a request using httpCpent.send() and get a response object.
Example
import java.io.IOException; import java.net.URI; import java.net.http.HttpCpent; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.time.Duration; pubpc class APITester { pubpc static void main(String[] args) { HttpCpent httpCpent = HttpCpent.newBuilder() .version(HttpCpent.Version.HTTP_2) .connectTimeout(Duration.ofSeconds(10)) .build(); try { HttpRequest request = HttpRequest.newBuilder() .GET() .uri(URI.create("https://www.google.com")) .build(); HttpResponse<String> response = httpCpent.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println("Status code: " + response.statusCode()); System.out.println("Headers: " + response.headers().allValues("content-type")); System.out.println("Body: " + response.body()); } catch (IOException | InterruptedException e) { e.printStackTrace(); } } }
Output
It will print the following output.
Status code: 200 Headers: [text/html; charset=ISO-8859-1] Body: <!doctype html> ... </html>Advertisements