Imagine that you want to post the details of a form to a web application or web service programmatically. You can do so by sending a POST request, using the HTTP Client API. The following code uses the send() method from HttpClient to post a set of parameter names and values to a server. The parameter names and their values are stored as a String value:
public class HttpReqPost { public static void main(String uri[]) throws Exception { String postData = "?
name='Mala'&email='info@ejavaguru
@gmail.com'"; HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("http://www.ejavaguru.com/Java11/register.php")) .POST(BodyPublishers.ofString(postData)) .build(); HttpResponse<?> response = client.send(request,
BodyHandlers.discarding()); System.out.println(response.statusCode()); } }
In the preceding code, the HttpRequest builder includes the following code:
.POST(BodyPublishers.ofString(postString)
The BodyPublishers class defines common implementations of BodyPublisher, which is a Reactive Stream to publish request body bytes to the server. BodyPublishers defines static methods as ofString, ofFile, ofInputStream, and ofByteArray to publish a request body from String, file, or InputStream, converting high-level Java types into a flow of data to be sent as a request body.
In this example, the POST data is stored in a string, postData, which is sent with the request to the server. In this case, I don't wish to process the received response from the server, so I use BodyHandlers.discarding() while accessing the response.
If you remember, all of the previous examples in this chapter used a Reactive Stream to receive the response body bytes from the server in a non-blocking and asynchronous manner. So, the HTTP Client enables you to send a request and receive responses to and from the server, using Reactive Streams.
When you work with the HTTP Client, you can also receive the response as a JSON, XML, or other data type. Similarly, you can also send multiple data types to a server. You can use the appropriate API from Java SE or another vendor to convert from one format to another.