10 Examples of New HTTP Client In Java
Until recently, Java handed only the HttpURLConnection API, which is low- position and is not known for being point-rich and friendly to users. Because of this, some extensively used third-party libraries were generally used, similar as Apache HttpClient, Jetty, and Spring's RestTemplate
Unlike the HttpURLConnection, HTTP Client gives synchronous and asynchronous request mechanisms.
The API includes 3 center classes:
HttpRequest represents the request to be dispatched along the HttpClient.
HttpClient behaves as a box for configuration statistics not an unusual place for more than one request.
HttpResponse represents the end result of an HttpRequest call.
We'll look at each of them in more significant detail within the following sections. First, let's pay attention to a request.
HttpClient Synchronous and Asynchronous Example
Let's first see the Synchronous example from Javadoc of how you can use HttpClient to send a synchronous request:
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<String> response = client.send(request, BodyHandlers.ofString());
System.out.println(response.statusCode());
System.out.println(response.body());
In this case, your program will send request and wait for response, once response is received it will print the status code and response body
Now, let's see an example of Asynchronous call to a REST API in Java using HttpClient API:
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://restres.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);
If you notice the difference here we have used sendAsync() method instead of send() method in case of previous example. This means, use HttpClient.send() to send a synchronous request and use HttpClient.sendAsync() to make an asynchronous request to any HTTP Server or RESTful Web Service.
1. HttpRequest
2. How To Set Up a URI
HttpRequest.newBuilder(new URI("https://restres.com/get")) HttpRequest.newBuilder() .uri(new URI("https://restres.com/get"))
3. How To Specify The HTTP Method
- GET()
- POST(BODYPUBLISHER Body)
- PUT(BODYPUBLISHER Body)
- DELETE()
HttpRequest request = HttpRequest.newBuilder() .uri(new URI("https://postman-echo.com/get")) .GET() .build();
4. How To Set Up The HTTP Protocol Version in HttpClient in Java
HttpRequest request = HttpRequest.newBuilder() .uri(new URI("https://postman-echo.com/get")) .version(HttpClient.Version.HTTP_2) .GET() .build();
5. How to Set Up Headers in HttpClient Java
HttpRequest request = HttpRequest.newBuilder() .uri(new URI("https://postman-echo.com/get")) .headers("key1", "value1", "key2", "value2") .GET() .build() HttpRequest request2 = HttpRequest.newBuilder() .uri(new URI("https://postman-echo.com/get")) .header("key1", "value1") .header("key2", "value2") .GET() .build();
6. How To Set Up a Timeout with HttpClient in Java
HttpRequest request = HttpRequest.newBuilder() .uri(new URI("https://postman-echo.com/get")) .timeout(Duration.of(10, SECONDS)) .GET() .build()
7. How to Set a Request Body using HttpClient in Java
HttpRequest request = HttpRequest.newBuilder() .uri(new URI("https://postman-echo.com/post")) .POST(HttpRequest.BodyPublishers.noBody()) .build();
8. How To Use The StringBodyPublisher in HttpClient Java
HttpRequest request = HttpRequest.newBuilder() .uri(new URI("https://postman-echo.com/post")) .headers("Content-Type", "text/plain;charset=UTF-8") .POST(HttpRequest.BodyPublishers.ofString("Sample request body")) .build();
9. How To Use InputStreamBodyPublisher in HttpClient in Java
byte[] sampleData = "Sample request body".getBytes(); HttpRequest request = HttpRequest.newBuilder() .uri(new URI("https://postman-echo.com/post")) .headers("Content-Type", "text/plain;charset=UTF-8") .POST(HttpRequest.BodyPublishers .ofInputStream(() -> new ByteArrayInputStream(sampleData))) .build();
10. How to Use the ByteArrayProcessor in Java HttpClient
byte[] sampleData = "Sample request body".getBytes(); HttpRequest request = HttpRequest.newBuilder() .uri(new URI("https://postman-echo.com/post")) .headers("Content-Type", "text/plain;charset=UTF-8") .POST(HttpRequest.BodyPublishers.ofByteArray(sampleData)) .build();
HtttpClient Frequently Asked Questions in Java
- Why Spring MVC is best to create REST API in Java (article)
- 5 Best Courses to learn RESTful Web Service using Spring (best courses)
- Top 10 Java Web service interview questions (see here)
- Top 10 RESTful web services interview questions for Java developers (see)
- REST Web Services framework Interview Question (see here)
- Top 5 Courses to learn Spring MVC (online courses)
- 10 Free Spring Boot courses for beginners (free courses)
- 10 REST API Books for Web Developers (books)
- Difference between SOAP and RESTful web service in Java? (see here)
- 10 Microservice and Spring courses in Java (online courses)
- What are idempotent and safe methods of HTTP and REST? (answer)
- What is the purpose of different HTTP methods in REST? (answer)
- 5 Books to prepare Java EE interviews (list)
- 5 courses to learn Spring framework in depth (courses)
- Top 5 Books to Learn REST and RESTful Web Services? (books)
- 10 Best Courses to learn Spring Framework (best courses)
- Top 5 Courses to learn RESTFul Web Services in Java (courses)
P. S. - If you are looking for online training to learn how to develop RESTful Web Services in Java using the Spring framework, I suggest you joining Eugen Paraschiv's REST with Spring course. The course has various options depending upon your experience level and how much you want to learn like beginner's class, intermediate class, and master class.
No comments:
Post a Comment
Feel free to comment, ask questions if you have any doubt.