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