View Javadoc
1   /*
2    * ====================================================================
3    * Licensed to the Apache Software Foundation (ASF) under one
4    * or more contributor license agreements.  See the NOTICE file
5    * distributed with this work for additional information
6    * regarding copyright ownership.  The ASF licenses this file
7    * to you under the Apache License, Version 2.0 (the
8    * "License"); you may not use this file except in compliance
9    * with the License.  You may obtain a copy of the License at
10   *
11   *   http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing,
14   * software distributed under the License is distributed on an
15   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16   * KIND, either express or implied.  See the License for the
17   * specific language governing permissions and limitations
18   * under the License.
19   * ====================================================================
20   *
21   * This software consists of voluntary contributions made by many
22   * individuals on behalf of the Apache Software Foundation.  For more
23   * information on the Apache Software Foundation, please see
24   * <http://www.apache.org/>.
25   *
26   */
27  package org.apache.hc.client5.http.examples;
28  
29  import java.io.IOException;
30  import java.net.URI;
31  import java.nio.ByteBuffer;
32  import java.util.List;
33  import java.util.concurrent.CountDownLatch;
34  import java.util.concurrent.TimeUnit;
35  
36  import org.apache.hc.client5.http.impl.async.HttpAsyncClients;
37  import org.apache.hc.client5.http.impl.async.MinimalHttpAsyncClient;
38  import org.apache.hc.core5.http.ContentType;
39  import org.apache.hc.core5.http.EntityDetails;
40  import org.apache.hc.core5.http.Header;
41  import org.apache.hc.core5.http.HttpException;
42  import org.apache.hc.core5.http.HttpResponse;
43  import org.apache.hc.core5.http.config.Http1Config;
44  import org.apache.hc.core5.http.nio.AsyncClientExchangeHandler;
45  import org.apache.hc.core5.http.nio.CapacityChannel;
46  import org.apache.hc.core5.http.nio.DataStreamChannel;
47  import org.apache.hc.core5.http.nio.RequestChannel;
48  import org.apache.hc.core5.http.nio.entity.BasicAsyncEntityProducer;
49  import org.apache.hc.core5.http.nio.entity.StringAsyncEntityConsumer;
50  import org.apache.hc.core5.http.nio.support.BasicRequestProducer;
51  import org.apache.hc.core5.http.nio.support.BasicResponseConsumer;
52  import org.apache.hc.core5.http.protocol.HttpContext;
53  import org.apache.hc.core5.http2.HttpVersionPolicy;
54  import org.apache.hc.core5.http2.config.H2Config;
55  import org.apache.hc.core5.io.CloseMode;
56  import org.apache.hc.core5.reactor.IOReactorConfig;
57  import org.apache.hc.core5.util.Timeout;
58  
59  /**
60   * This example demonstrates a full-duplex, streaming HTTP/1.1 message exchange.
61   */
62  public class AsyncClientFullDuplexExchange {
63  
64      public static void main(final String[] args) throws Exception {
65  
66          final IOReactorConfig ioReactorConfig = IOReactorConfig.custom()
67                  .setSoTimeout(Timeout.ofSeconds(5))
68                  .build();
69  
70          final MinimalHttpAsyncClient client = HttpAsyncClients.createMinimal(
71                  HttpVersionPolicy.NEGOTIATE,
72                  H2Config.DEFAULT,
73                  Http1Config.DEFAULT,
74                  ioReactorConfig);
75  
76          client.start();
77  
78          final URI requestUri = new URI("http://httpbin.org/post");
79          final BasicRequestProducer requestProducer = new BasicRequestProducer(
80                  "POST", requestUri, new BasicAsyncEntityProducer("stuff", ContentType.TEXT_PLAIN));
81          final BasicResponseConsumer<String> responseConsumer = new BasicResponseConsumer<>(
82                  new StringAsyncEntityConsumer());
83  
84          final CountDownLatch latch = new CountDownLatch(1);
85          client.execute(new AsyncClientExchangeHandler() {
86  
87              @Override
88              public void releaseResources() {
89                  requestProducer.releaseResources();
90                  responseConsumer.releaseResources();
91                  latch.countDown();
92              }
93  
94              @Override
95              public void cancel() {
96                  System.out.println(requestUri + " cancelled");
97              }
98  
99              @Override
100             public void failed(final Exception cause) {
101                 System.out.println(requestUri + "->" + cause);
102             }
103 
104             @Override
105             public void produceRequest(final RequestChannel channel, final HttpContext context) throws HttpException, IOException {
106                 requestProducer.sendRequest(channel, context);
107             }
108 
109             @Override
110             public int available() {
111                 return requestProducer.available();
112             }
113 
114             @Override
115             public void produce(final DataStreamChannel channel) throws IOException {
116                 requestProducer.produce(channel);
117             }
118 
119             @Override
120             public void consumeInformation(
121                     final HttpResponse response,
122                     final HttpContext context) throws HttpException, IOException {
123                 System.out.println(requestUri + "->" + response.getCode());
124             }
125 
126             @Override
127             public void consumeResponse(
128                     final HttpResponse response,
129                     final EntityDetails entityDetails,
130                     final HttpContext context) throws HttpException, IOException {
131                 System.out.println(requestUri + "->" + response.getCode());
132                 responseConsumer.consumeResponse(response, entityDetails, context, null);
133             }
134 
135             @Override
136             public void updateCapacity(final CapacityChannel capacityChannel) throws IOException {
137                 responseConsumer.updateCapacity(capacityChannel);
138             }
139 
140             @Override
141             public void consume(final ByteBuffer src) throws IOException {
142                 responseConsumer.consume(src);
143             }
144 
145             @Override
146             public void streamEnd(final List<? extends Header> trailers) throws HttpException, IOException {
147                 responseConsumer.streamEnd(trailers);
148             }
149 
150         });
151         latch.await(1, TimeUnit.MINUTES);
152 
153         System.out.println("Shutting down");
154         client.close(CloseMode.GRACEFUL);
155     }
156 
157 }