New features of JDK11: HTTP API and reactive streams

brief introduction

stay New features of JDK11: new HTTP API In, we describe the new HTTP API that allows us to send synchronous or asynchronous requests and get the results returned.

Today we want to explore the relationship between these synchronous or asynchronous requests and responses and reactive streams.

More please visit

How to use reactive streams in java

Introduction to reactive streams for your reference reactive stream protocol details , the purpose of using reactive streams is to solve the communication problem between sender and consumer, sender will not send information beyond consumer's ability.

Let's review a few key concepts in reactive streams:

  • Publisher is responsible for generating messages or events and provides a subscribed interface to connect to Subscriber.

  • Subscriber is used to subscribe a Publisher and provides onNext methods to handle new messages, onError to handle exceptions, and onComplete to provide Publisher calls to end listening.

  • Subscription is responsible for connecting Publisher to Subscriber and can be used to request messages or cancel listening.

Further, if we want to implement a reactive streams on our own, we need to do these things:

  1. Create Publisher and Subscriber
  • Create Publisher and Subscriber.
  • Call Publisher.subscribe(Subscriber) to establish a connection between Publisher and Subscriber.
  • Publisher creates a Subscription and calls the Subscriber.onSubscription(Subscription) method.
  • Subscriber saves the Subscription for later use.
  1. Send and receive information
  • Subscriber calls the Subscription.request(n) method to request n messages.
  • Publisher calls Subscriber.onNext(item) to send the requested message to Subscriber.
  • Repeat the appeal process as needed.
  1. Cancel or End
  • Publisher calls the Subscriber.OnError(err) or Subscriber.onComplete() methods.
  • Subscriber calls the Subscription.cancel() method.

Example of a POST request

Remember the example we used in the last article when we talked about new features of the HTTP API?

For example, we use an HttpRequest.BodyPublisher to construct a Post request, and BodyPublisher is a Flow.Publisher:

public interface BodyPublisher extends Flow.Publisher<ByteBuffer>

That is, reactive streams have been used since BodyPublisher.

To better understand how reactive streams work, we create several wrapper classes that wrap Publisher, Subscriber, and Subscription together and output the appropriate logs.

With a bit more code, we don't have to list it all. Here's just a specific implementation of CustBodyPublisher:

public class CustBodyPublisher implements HttpRequest.BodyPublisher {

    private final HttpRequest.BodyPublisher bodyPublisher;

    public CustBodyPublisher(HttpRequest.BodyPublisher bodyPublisher){
    public long contentLength() {
        long contentLength=bodyPublisher.contentLength();"contentLength:{}",contentLength);
        return contentLength;

    public void subscribe(Flow.Subscriber<? super ByteBuffer> subscriber) {"CustBodyPublisher subscribe {}",subscriber);
        bodyPublisher.subscribe(new CustSubscriber(subscriber));

The wrapper class is simple, passing in the class to wrapper through the constructor, and calling the method of the actual wrapper class in the corresponding method.

Finally, we'll revamp the previous example of calling the HTTP API:

    public void testCustPost() throws IOException, InterruptedException {
        HttpClient client = HttpClient.newBuilder().build();

        HttpRequest.BodyPublisher requestBody = HttpRequest.BodyPublishers
                .ofString("{ I am body }");
        CustBodyPublisher custBodyPublisher= new CustBodyPublisher(requestBody);
        HttpRequest postRequest = HttpRequest.newBuilder()

        HttpResponse<String> response = client
                .send(postRequest, HttpResponse.BodyHandlers.ofString());"response {}",response);

Notice here that CustBodyPublisher custBodyPublisher= new CustBodyPublisher(requestBody), and we created a new wrapper class.

Run it and observe the output:

[HttpClient-1-Worker-0] INFO com.flydean.CustBodyPublisher - contentLength:14
[HttpClient-1-Worker-0] INFO com.flydean.CustBodyPublisher - CustBodyPublisher subscribe$FixedContentSubscriber@672776b6
[HttpClient-1-Worker-0] INFO com.flydean.CustSubscriber - CustSubscriber onSubscribe$Subscription@580ce038
[HttpClient-1-Worker-0] INFO com.flydean.CustSubscription - CustSubscription request 1
[HttpClient-1-Worker-0] INFO com.flydean.CustSubscriber - CustSubscriber onNext length 14
[HttpClient-1-Worker-0] INFO com.flydean.CustSubscription - CustSubscription request 1
[HttpClient-1-Worker-0] INFO com.flydean.CustSubscriber - CustSubscriber onComplete
[main] INFO com.flydean.ReactiveHttpUsage - response (POST 200

You can see the specific workflow of the reactive stream.CustBodyPublisher is created first, then the subscribe method is called.

CustSubscriber then calls onSubscribe to create the Subscription.

Each request method of CustSubscription causes the onNext method of CustSubscriber to be called.

Finally, when CustSubscription requests no results again, CustSubscriber calls the onComplete method to end the entire process.

Note that in the example above, we wrapper calls BodyPublishers.ofString, which actually has several implementations of BodyPublishers built into it.Interested friends can explore themselves.


This article explains the use of reactive Streams in the new HTTP API.

Examples of this article learn-java-base-9-to-20

Author: Fldean Programs

Links to this article:

Source: Fldean's blog

Welcome to my Public Number: program stuff, more exciting waiting for you!

Tags: Programming Java JDK github

Posted on Sat, 16 May 2020 20:24:46 -0400 by nasty_psycho