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  
28  package org.apache.hc.core5.http.examples;
29  
30  import java.nio.charset.StandardCharsets;
31  import java.util.concurrent.TimeUnit;
32  
33  import org.apache.hc.core5.http.ClassicHttpRequest;
34  import org.apache.hc.core5.http.ClassicHttpResponse;
35  import org.apache.hc.core5.http.ContentType;
36  import org.apache.hc.core5.http.HttpConnection;
37  import org.apache.hc.core5.http.HttpEntity;
38  import org.apache.hc.core5.http.HttpHost;
39  import org.apache.hc.core5.http.HttpRequest;
40  import org.apache.hc.core5.http.HttpResponse;
41  import org.apache.hc.core5.http.impl.Http1StreamListener;
42  import org.apache.hc.core5.http.impl.bootstrap.HttpRequester;
43  import org.apache.hc.core5.http.impl.bootstrap.RequesterBootstrap;
44  import org.apache.hc.core5.http.io.SocketConfig;
45  import org.apache.hc.core5.http.io.entity.EntityUtils;
46  import org.apache.hc.core5.http.io.entity.HttpEntities;
47  import org.apache.hc.core5.http.io.support.ClassicRequestBuilder;
48  import org.apache.hc.core5.http.message.BasicHeader;
49  import org.apache.hc.core5.http.message.RequestLine;
50  import org.apache.hc.core5.http.message.StatusLine;
51  import org.apache.hc.core5.http.protocol.HttpCoreContext;
52  import org.apache.hc.core5.util.Timeout;
53  
54  /**
55   * Example of POST requests execution using classic I/O.
56   */
57  public class ClassicPostExecutionExample {
58  
59      public static void main(final String[] args) throws Exception {
60          final HttpRequester httpRequester = RequesterBootstrap.bootstrap()
61                  .setStreamListener(new Http1StreamListener() {
62  
63                      @Override
64                      public void onRequestHead(final HttpConnection connection, final HttpRequest request) {
65                          System.out.println(connection.getRemoteAddress() + " " + new RequestLine(request));
66  
67                      }
68  
69                      @Override
70                      public void onResponseHead(final HttpConnection connection, final HttpResponse response) {
71                          System.out.println(connection.getRemoteAddress() + " " + new StatusLine(response));
72                      }
73  
74                      @Override
75                      public void onExchangeComplete(final HttpConnection connection, final boolean keepAlive) {
76                          if (keepAlive) {
77                              System.out.println(connection.getRemoteAddress() + " exchange completed (connection kept alive)");
78                          } else {
79                              System.out.println(connection.getRemoteAddress() + " exchange completed (connection closed)");
80                          }
81                      }
82  
83                  })
84                  .setSocketConfig(SocketConfig.custom()
85                          .setSoTimeout(5, TimeUnit.SECONDS)
86                          .build())
87                  .create();
88          final HttpCoreContext coreContext = HttpCoreContext.create();
89          final HttpHost target = new HttpHost("httpbin.org");
90  
91          final HttpEntity[] requestBodies = {
92                  HttpEntities.create(
93                          "This is the first test request",
94                          ContentType.TEXT_PLAIN.withCharset(StandardCharsets.UTF_8)),
95                  HttpEntities.create(
96                          "This is the second test request".getBytes(StandardCharsets.UTF_8),
97                          ContentType.APPLICATION_OCTET_STREAM),
98                  HttpEntities.create(outStream -> outStream.write(("This is the third test request " +
99                          "(streaming)").getBytes(StandardCharsets.UTF_8)), ContentType.TEXT_PLAIN.withCharset(StandardCharsets.UTF_8)),
100                 HttpEntities.create(
101                         "This is the fourth test request " +
102                                 "(streaming with trailers)",
103                         ContentType.TEXT_PLAIN.withCharset(StandardCharsets.UTF_8),
104                         new BasicHeader("trailer1","And goodbye"))
105         };
106 
107         final String requestUri = "/post";
108         for (int i = 0; i < requestBodies.length; i++) {
109             final ClassicHttpRequest request = ClassicRequestBuilder.get()
110                     .setHttpHost(target)
111                     .setPath(requestUri)
112                     .build();
113             request.setEntity(requestBodies[i]);
114             try (ClassicHttpResponse response = httpRequester.execute(target, request, Timeout.ofSeconds(5), coreContext)) {
115                 System.out.println(requestUri + "->" + response.getCode());
116                 System.out.println(EntityUtils.toString(response.getEntity()));
117                 System.out.println("==============");
118             }
119         }
120     }
121 
122 }